给定一个n行m列的字符数组(迷宫) 输入: 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]; // 判断当前位置是否合法(在迷宫数组中没有越界) 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; // 为了展示路径,将走过的路改成m maze[x][y] = 'm'; // 让他往上走 int tx = x - 1, ty = y; // 保证该位置在数组内,且不是墙壁,且未被访问过(如果之前被访问过说明之前的路径无法走出迷宫) if(in(tx, ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ if(dfs(tx, ty) == true) return true; } // 往上走不通 开始往左走 tx = x ; ty = y - 1; if(in(tx, ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ if(dfs(tx, ty) == true) return true; } // 往左走不通 开始往下走 tx = x + 1; ty = y; if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ if(dfs(tx, ty) == true) return true; } // 往下走不通 开始往右走 tx = x ; ty = y + 1; if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ if(dfs(tx,ty) == true) return true; } // 如果没找到,则将当前位置标记为未被访问,方便下一次dfs vis[x][y] = false; // 没找到,将路径恢复成原状,方便下次dfs 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-15 22:53:16 发布