宽度优先搜索,即BFS,有时也叫做广度优先搜索。与深度优先搜索的一条路走到黑不同,它是先遍历离自己最近的一些点,然后逐步向更远的路径进行搜索。它利用的是队列来完成这一操作。在这道迷宫求解问题中它的时间复杂度约为O(MxN)。另外,对于bfs而言,通常我们需要建立一个结构体来储存当前的坐标和当前路径的长度。在我们实际算法竞赛中,如果dfs和bfs都能解决的问题,我们尽可能用bfs,因为dfs会存在栈溢出的问题。
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class node{
int x,y,d;
node(int xx,int yy,int dd){
x=xx;
y=yy;
d=dd;
}
}
static int n,m,x1=0,y1=0,ans;
static char[][] map;
static boolean vis[][];
static int[] dx= {1,-1,0,0};
static int[] dy= {0,0,1,-1};
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
int x=0,y=0;
sc.nextLine();
map=new char[n][m];
vis=new boolean[n][m];
for(int i=0;i<n;i++) {
map[i]=sc.nextLine().toCharArray();
for(int j=0;j<m;j++) {
if(map[i][j]=='S') {
x=i;y=j;
}
if(map[i][j]=='G') {
x1=i;y1=j;
}
}
}
bfs(x,y);
System.out.println(ans);
}
public static void bfs(int x,int y) {
Queue<node> q=new LinkedList<node>();
q.add(new node(x,y,0));
vis[x][y]=true;
while(!q.isEmpty()) {
node now=q.remove();
for(int i=0;i<4;i++) {
int tx=now.x+dx[i];
int ty=now.y+dy[i];
int td=now.d+1;
if(0<=tx&&tx<n&&0<=ty&&ty<m&&map[tx][ty]!='#'&&!vis[tx][ty]) {
if(tx==x1&&ty==y1) {
ans=td;
return;
}
vis[tx][ty]=true;
q.add(new node(tx,ty,td));
}
}
}
}
}