首页 > 代码库 > Java --- 走迷宫

Java --- 走迷宫

走迷宫需要考虑大量的实验和错误:沿着一条路径走,当不能再向前走时回溯,然后尝试另一条以前没尝试过的选择。可是使用递归算法。

//**********************************************************// MaseSearch.java//**********************************************************public class MaseSearch {	public static void main(String[] args)	{		Mase labyrinth = new Mase();				System.out.println(labyrinth);				if(labyrinth.traverse(0,0))			System.out.println("The Mase was successfully traversed!");		else			System.out.println("There is no possble path");				System.out.println(labyrinth);	}}//**********************************************************// Mase.java//**********************************************************public class Mase {	private final int TRIED = 3;	private final int PATH = 7;		private int[][] grid={{1,1,1,0,1,1,0,0,0,1,1,1,1},			              {1,0,1,1,1,0,1,1,1,1,0,0,1},			              {0,0,0,0,1,0,1,0,1,0,1,0,0},			              {1,1,1,0,1,1,1,0,1,0,1,1,1},			              {1,0,1,0,0,0,0,1,1,1,0,0,1},			              {1,0,1,1,1,1,1,1,0,1,1,1,1},			              {1,0,0,0,0,0,0,0,0,0,0,0,0},			              {1,1,1,1,1,1,1,1,1,1,1,1,1}};		public boolean traverse(int row,int column)	{		boolean done = false;				if(valid(row,column))  // 判断是否为1 ,为1 则真		{			grid[row][column] = TRIED;						if(row == grid.length-1 && column == grid[0].length-1)				done = true;			else			{				done = traverse(row+1,column);				if(!done)					done = traverse(row,column+1);				if(!done)					done = traverse(row-1,column);				if(!done)					done = traverse(row,column-1);			}			if(done)				grid[row][column]=PATH;		}		return done;	}		private boolean valid(int row,int column)	{		boolean result = false;		if(row>=0 && row<grid.length && column >= 0 && column < grid[row].length)			if(grid[row][column] == 1)				result = true;				return result;	}		public String toString()	{		String result = "\n";		for(int row = 0;row < grid.length;row++)		{			for(int column=0; column<grid[row].length;column++)				result += grid[row][column] + " ";				result += "\n";		}		return result;	}}

 

  

 

 

  

 

 

  

 

Java --- 走迷宫