题解 | #走迷宫#
走迷宫
https://www.nowcoder.com/practice/e88b41dc6e764b2893bc4221777ffe64
总结:
1.需要考虑终点有障碍这一特殊情况。
2.使用广度优先搜索可以解决这一问题,将无障碍的网格表示为1,有障碍或被访问过都表示为0.
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String[] line = sc.nextLine().split(" "); int n = Integer.parseInt(line[0]); int m = Integer.parseInt(line[1]); int[][] path = new int[n+1][m+1]; line = sc.nextLine().split(" "); int x1 = Integer.parseInt(line[0]); int y1 = Integer.parseInt(line[1]); int x2 = Integer.parseInt(line[2]); int y2 = Integer.parseInt(line[3]); int i = 1,j=1; while(sc.hasNextLine()){ char[] ch = sc.nextLine().toCharArray(); for(char c:ch){ if(c=='.') path[i][j] = 1; j++; } i++; j = 1; } System.out.println(bfs(x1,y1,x2,y2,path)); } public static int bfs(int x1,int y1,int x2,int y2,int[][] path){ Queue<int[]> queue = new LinkedList<>(); queue.add(new int[]{x1,y1,0}); int n = path.length-1; int m = path[0].length-1; path[x1][y1]=0; if(path[x2][y2]==0) return -1; while(!queue.isEmpty()){ int[] a = queue.poll(); if(a[0]+1==x2&&a[1]==y2) return a[2]+1; if(a[0]-1==x2&&a[1]==y2) return a[2]+1; if(a[0]==x2&&a[1]+1==y2) return a[2]+1; if(a[0]==x2&&a[1]-1==y2) return a[2]+1; if(a[0]+1<=n&&path[a[0]+1][a[1]]==1){ queue.add(new int[]{a[0]+1,a[1],a[2]+1}); path[a[0]+1][a[1]]=0; } if(a[0]-1>=1&&path[a[0]-1][a[1]]==1){ queue.add(new int[]{a[0]-1,a[1],a[2]+1}); path[a[0]-1][a[1]]=0; } if(a[1]+1<=m&&path[a[0]][a[1]+1]==1){ queue.add(new int[]{a[0],a[1]+1,a[2]+1}); path[a[0]][a[1]+1]=0; } if(a[1]-1>=1&&path[a[0]][a[1]-1]==1){ queue.add(new int[]{a[0],a[1]-1,a[2]+1}); path[a[0]][a[1]-1]=0; } } return -1; } }