一次将一个节点的所有相邻节点都遍历,然后再依次遍历相邻节点的相邻节点,依此类推。
使用队列作为辅助的数据结构。
广度优先遍历求出了无权图的最短路径
迷宫问题,
import java.util.LinkedList;
import java.util.Queue;
//广度优先搜索
class MAN{
int x;//坐标
int y;//坐标
int s;//步数
MAN(int x,int y,int s){
this.x =x;
this.y=y;
this.s =s;
}
}
public class BFS {
int next[][] = {{0,1},{1,0},{0,-1},{-1,0}};
int book[][] = new int[20][20];
int flag =0;
int tx,ty;
public void bfs(int a[][],int x,int y,int m,int n,int p,int q){
Queue<MAN> queue = new LinkedList<MAN>();
MAN node = new MAN(x,y,0);
queue.add(node);
book[x][y] = 1;
while(!queue.isEmpty()){
for(int k=0;k<4;k++){
tx = queue.peek().x+next[k][0];
ty = queue.peek().y+next[k][1];
if(tx>=m||ty>=n||tx<0||ty<0)
{
continue;
}
if(a[tx][ty]==0&&book[tx][ty]==0)
{
book[tx][ty] = 1;
int s =queue.element().s;
MAN node1 = new MAN(tx,ty,s+1);
queue.add(node1);
}
if(tx==p-1&&ty==q-1)
{
flag =1;
while(queue.size()!=1){
queue.remove();
}
break;
}
}
if(flag ==1){
break;
}
queue.poll();
}
int end = queue.element().s;
System.out.println(end);
}
public static void main(String[] args) {
BFS bfs = new BFS();
int a[][]={{0,0,1,0},{0,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1}};
bfs.bfs(a, 0, 0, 5, 4, 4, 3);
}
}