您当前的位置: 首页 >  Java

星拱北辰

暂无认证

  • 0浏览

    0关注

    1205博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Java】走迷宫

星拱北辰 发布时间:2019-09-28 14:42:49 ,浏览量:0

//Represents a maze of characters.
//The goal is to get from the top left corner to the bottom right, following a path of 1s.
//走1不走0的迷宫的递归实现

public class Maze {	
	private final int TRIED = 3;
	private final int PATH = 7;
	
	//二维数组创建8×13大矩阵作为迷宫
	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}};
	
	//Attempts to recursively traverse the maze.
	//Inserts special characters indicating locations that have been tried
	//	and that eventually become part of the solution.
	/*基本实际情况有三种:
	 * 移动操作由于出界而无效
	 * 移动操作由于以前尝试过而无效
	 * 移动操作达到最终位置
	 */
	public boolean traverse(int row, int column) {		
		boolean done = false;
		
		if (valid(row, column)) {
			//搜过的就是死路一条
			grid[row][column] = TRIED;			//This cell has been tried.
			
			if (row == grid.length-1 && column == grid[0].length-1) 
				done = true;		//The maze is solved;
			else {
				//搜索顺序:下→右→上→左,因为要从左上到右下,自然是要优先搜索下和右
				done = traverse(row+1, column);			//down
				if (!done)
					done = traverse(row, column+1);		//right
				if (!done)
					done = traverse(row-1, column);		//up
				if (!done)
					done = traverse(row, column-1);		//left
			}
			
			if (done)	//This location id=s part of the final path
				grid[row][column] = PATH;
		}
		//无路可走返回false
		return done;
	}
	
	//Determines if a special location is valid.
	//防止搜索中的非法越界
	private boolean valid(int row, int column) {
		boolean result = false;
		
		//check if cell is in the bounds of the matrix.
		if (row >= 0 && row = 0 && column             
关注
打赏
1660750074
查看更多评论
0.0497s