将四个方向归纳为一个数组,换方向代码少写了3/4 输入; 5 6 ....S* .***.. .*..*. *.***. .T.... 输出: ....m* .***mm .*..*m *.***m .Tmmmm import java.util.*; public class LANQIAO1 { public static int n; // 行 public static int m; // 列 public static String[] tmp = new String[110]; // 字符串数组用于给字符数组赋值 public static char[][] maze = new char[110][110]; public static boolean[][] vis = new boolean[110][110]; // 方向数组(x,y 的增量)(逆时针),用于给当前位置加数表示从当前位置,往上 左 下 右 移动 public static int[][] dir = {{-1,0},{0,-1},{1,0},{0,1}}; // 判断当前位置是否合法(在迷宫数组中没有越界) public static boolean in(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } // 返回能不能走出去 public static boolean dfs(int x, int y){ if(maze[x][y] == 'T') { return true; } vis[x][y] = true; maze[x][y] = 'm'; for (int i = 0; i < 4; i++) { int tx ,ty ; tx = x + dir[i][0]; ty = y + dir[i][1]; if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ if(dfs(tx,ty)){ return true; } } } // 如果找不到终点则取消标记 vis[x][y] = false; maze[x][y] = '.'; // 该点不行,返回上一级尝试下一个方向 return false; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); for(int i = 0; i < n; i++){ tmp[i] = sc.next(); } // 串数组给字符数组赋值 for(int i = 0; i < n ; i++){ for(int j = 0; j < m; j++){ maze[i][j] = tmp[i].charAt(j); } } // 先找出起始点,才能知道从哪开始搜 int x = 0,y = 0 ; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(maze[i][j] == 'S'){ x = i;y = j; } } } // 找到终点,打出地图 if(dfs(x,y)){ for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.print(maze[i][j]); } System.out.println(); } }else { System.out.println("NO"); } } }
蓝桥杯算法dfs迷宫问题优化
最新推荐文章于 2024-07-19 15:45:46 发布