首页 > 代码库 > 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 --- 走迷宫
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。