InputThe input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
OutputFor each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.Sample Inputjava
4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
Sample Outputexpress
66 88 66
題意:求2個點到同一個點的最短路程
注意:某些點可能兩個點不能同時到達,因此要用兩個數組分別記錄兩次廣搜的路徑到達狀況
仍是強調多個輸入,每次都要數組初始化、隊列清空
代碼:
import java.util.ArrayDeque; import java.util.Arrays; import java.util.Scanner; class Node{ int x; int y; int step; public Node(int x,int y,int step){ this.x=x; this.y=y; this.step=step; } } public class Main{ static final int N=205; static int n,m; static int dx[]={0,0,1,-1}; static int dy[]={1,-1,0,0}; static char map[][]=new char[N][N]; static int s1[][]=new int[N][N]; static int s2[][]=new int[N][N]; static boolean vis[][]=new boolean[N][N]; static ArrayDeque<Node> q=new ArrayDeque<Node>(); static void init(){ for(int i=0;i<N;i++) Arrays.fill(s1[i], 0); for(int i=0;i<N;i++) Arrays.fill(s2[i], 0); } static void bfs(int sx,int sy,int s[][]){ while(!q.isEmpty()) q.poll(); vis[sx][sy]=true; q.offer(new Node(sx,sy,0)); while(!q.isEmpty()){ Node t=q.poll(); for(int i=0;i<4;i++){ int xx=t.x+dx[i]; int yy=t.y+dy[i]; if(xx<0||yy<0||xx>=n||yy>=m ||vis[xx][yy]||map[xx][yy]=='#') continue; vis[xx][yy]=true; s[xx][yy]=t.step+1; q.offer(new Node(xx,yy,t.step+1)); } } } public static void main(String[] args) { Scanner scan=new Scanner(System.in); while(scan.hasNext()){ n=scan.nextInt(); m=scan.nextInt(); for(int i=0;i<n;i++) map[i]=scan.next().toCharArray(); int yx=0,yy=0,mx=0,my=0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(map[i][j]=='Y'){ yx=i; yy=j; } else if(map[i][j]=='M'){ mx=i; my=j; } init(); for(int i=0;i<N;i++) Arrays.fill(vis[i], false); bfs(yx,yy,s1); for(int i=0;i<N;i++) Arrays.fill(vis[i], false); bfs(mx,my,s2); int min=2147483647; for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(map[i][j]=='@' && s1[i][j]!=0 &&s2[i][j]!=0) min=Math.min(min, s1[i][j]+s2[i][j]); System.out.println(min*11); } } }