迷宫求解_学习记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37770023/article/details/82826520

迷宫求解_学习记录

package p37;

/**
 * 迷宫求解
 * @author Guozhu Zhu
 * @date 2018/9/8
 * @version 1.0
 *
 */
public class Maze {
	
	/* ========== Test ========== */
	public static void main(String[] args) {
		int[][] grid = {		
				{1, 1, 1, 1, 1, 1},
				{1, 0, 1, 0, 1, 0},
				{0, 0, 1, 0, 1, 0},
				{1, 1, 1, 1, 1, 1}};
		boolean res = traverse(0, 0, grid);
		System.out.println(res);
		for (int i = 0; i < grid.length; i++) {
			for (int j = 0; j < grid[0].length; j++) {
				System.out.print(grid[i][j]);
			}
			System.out.println("");
		}
	}
	
	public static boolean traverse(int row, int col, int[][]grid) {
		boolean done = false;
		if (valid(row, col, grid)) {
			grid[row][col] = 2;
			if (row == grid.length-1 && col == grid[0].length-1) {
				done = true;
			} else {
				done = traverse(row+1, col, grid);
				if (!done) {
					done = traverse(row, col+1, grid);
				}
				if (!done) {
					done = traverse(row-1, col, grid);
				}
				if (!done) {
					done = traverse(row, col-1, grid);
				}
			}
			if (done) {
				grid[row][col] = 3;
			}
		}
		return done;
	}
	
	public static boolean valid(int row, int col, int[][] grid) {
		boolean res = false;
		if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length) {
			if (grid[row][col] == 1) {
				res = true;
			}
		}
		return res;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_37770023/article/details/82826520