穿越雷区(Java–BFS解法)
题目链接:http://oj.ecustacm.cn/problem.php?id=1266
解题代码(内含注释思路)
import java.util.*;public class Main {static int[][] dir = {{0,1},{0,-1},{1,0},{-1,0}};static String[][] map = new String[100][100];static int[][] vis = new int[100][100];public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();for(int i=0;i<n;i++)for(int j=0;j<n;j++) map[i][j] = sc.next();int ax=0,ay=0,bx=0,by=0;for(int i=0;i<n;i++)//计算起点坐标、终点坐标for(int j=0;j<n;j++) {ax = (map[i][j].equals("A") ? i:ax); ay = (map[i][j].equals("A") ? j:ay);bx = (map[i][j].equals("B") ? i:bx); by = (map[i][j].equals("B") ? j:by);}Queue<Node> queue = new LinkedList<>();queue.add(new Node(ax,ay,0,"0"));while(!queue.isEmpty()){Node node = queue.poll();//出界考虑,跳过if (node.x<0||node.x>=n||node.y<0||node.y>=n) continue;//违规走法被拒绝,跳过【不能连续++,不能连续--】if (node.last.equals(map[node.x][node.y])) continue;//访问过的节点,跳过,保证只输出一条路的结果//并且绝对是最短的if (vis[node.x][node.y] >= 1) continue;vis[node.x][node.y]++;//访问过就记录上,访问次数if (node.x==bx&&node.y==by)//到达了终点System.out.println(node.footNum);//四向扩散查终点for (int i = 0; i < 4; i++)queue.add(new Node(node.x+dir[i][0],node.y+dir[i][1],node.footNum+1,map[node.x][node.y]));}}}class Node{int x,y;int footNum;String last;public Node(int x,int y,int footNum,String last) {this.x=x;this.y=y;this.footNum =footNum;this.last=last;}
}