Java实现广度优先遍历bfs
程序员文章站
2022-05-22 21:00:39
...
import java.util.*;
public class Main{
static int N=210;
static int r ,c;;//必须在函数外定义为静态 r为行,c为列 方便下面使用
static int[][] dist = new int[N][N];
static char[][] f = new char [N][N];
static Queue<AbstractMap.SimpleEntry<Integer,Integer>> queue = new ArrayDeque<>();// 理解为设置一个队列 先进先出
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0){
r = in.nextInt();
c = in.nextInt();
for(int i=0;i<r;i++){
f[i] = in.next().toCharArray(); //因为这里指针从零开始 下面索引也要从零开始!!!!
}
int m=0,n=0;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
dist[i][j] = -1;
if(f[i][j] == 'S'){
m=i;n=j;
}
}
}
bfs(m,n);
}
}
public static void bfs(int i,int j){
queue.add(new AbstractMap.SimpleEntry<>(i,j));
int[] x = {-1,0,1,0};
int[] y = {0,1,0,-1};
f[i][j]='#';
dist[i][j]=0;
while(!queue.isEmpty()){//为空说明无路可走
int x1,y1;
AbstractMap.SimpleEntry<Integer, Integer> remove = queue.remove();
for(int z=0;z<4;z++){
x1 = remove.getKey()+x[z];
y1 = remove.getValue()+y[z];
if(x1<r&&x1>=0&&y1<c&&y1>=0&&f[x1][y1]!='#'&&dist[x1][y1]==-1){ //注意边界问题
if(f[x1][y1]=='.'){
dist[x1][y1]=dist[remove.getKey()][remove.getValue()]+1;
f[x1][y1]='#';
queue.add(new AbstractMap.SimpleEntry<>(x1,y1));
}
if(f[x1][y1]=='E'){
dist[x1][y1]=dist[remove.getKey()][remove.getValue()]+1;
queue.add(new AbstractMap.SimpleEntry<>(x1,y1));
System.out.println(dist[x1][y1]);
queue.clear(); //多组数据 需要及时清理
return;
}
}
}
}
if(queue.isEmpty()){
queue.clear();
System.out.println("oop!");
return;
}
}
}
上一篇: 深度优先DFS和广度优先BFS