输入: 5 6 ....S* .**... .*..*. *..**. .T.... 输出: 7 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 f; public static int ans = 1000000000; // 判断当前位置是否合法(在迷宫数组中没有越界) public static boolean in(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } // 返回能不能走出去 public static void dfs(int x ,int y, int step){ if(maze[x][y] == 'T'){ if(step < ans){ ans = step; } return; } vis[x][y] = true; for (int i = 0; i < 4; i++) { int tx = x + dir[i][0]; int ty = y + dir[i][1]; if(in(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){ dfs(tx,ty,step + 1); } } // 取消标记,因为以后还要搜 vis[x][y] = 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; } } } // 找到终点,打出地图 dfs(x, y, 0); System.out.println(ans); } }
蓝桥杯算法-迷宫问题最优解(dfs)
最新推荐文章于 2024-03-26 12:55:58 发布
这篇文章介绍了一种使用Java编程实现的迷宫求解算法,通过深度优先搜索(DFS)方法找到从起点S到终点T的最短路径,利用二维数组和布尔数组记录路径状态。
摘要由CSDN通过智能技术生成