- 类似于层次遍历
- 首先访问起始顶点v,
- v出发,依次访问领接的顶点
w1,w2,...,wi
不后退,一步可以访问一批结点
//结果:abcdefgh
bool visited[MAX_VERTEX_NUM];
void BFSTraverse(Graph G){
for(i=0;i<G.vexnum;++i)
visited[i]=FALSE
InitQueue(Q);
for(i=0;i<G.vexnum;++i)
if(!visited[i])
BFS(G,i);
}
void BFS(Graph G, int v){
visit(v);
visited[v]=TRUE;
Enqueue(Q,v);
while(!isEmpty(Q)){
DeQueue(Q,v);
for(w=FristNeighbor(G,v);w>=0;w=NextNeighbor(G,v,w))
if(!visited[w])
visited(w);
visited[w]=TRUE;
EnQueue(Q,w);
}
}
- 复杂度
借助队列工作:空间复杂度:O(|V|)
领接矩阵:查找每个顶点的时间复杂度是
O(|v|2)
领接表:查找的时间(O(|E|)),访问的时间O(|v|); 总时间=O(|V|+|E|)
迷宫最短路径
- 给定一个大小是N*M的迷宫,每一步向领接的上下左右四格的通道移动。请求出从起点到终点所需的最小步数
条件:N,M<=100
* 输入
N=10,M=10
#: 墙壁;.:通道; S:起点 G:终点
#S########
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
输出:22
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x,y,step;
};
char map[105][105];
int vis[105][105];
int to[4][2]= {1,0,-1,0,0,1,0,-1};
int n,m,sx,sy,ex,ey,ans;
int check(int x,int y)
{
if(x<0 || x>=n || y<0 || y>=m)
return 1;
if(vis[x][y] || map[x][y]=='#')
return 1;
return 0;
}
void bfs()
{
int i;
queue<node> Q;
node a,next;
a.x = sx;
a.y = sy;
a.step = 0;
vis[a.x][a.y]=1;
Q.push(a);
while(!Q.empty())
{
a = Q.front();
Q.pop();
if(map[a.x][a.y]=='E')
{
ans = a.step;
return ;
}
for(i = 0; i<4; i++)
{
next = a;
next.x+=to[i][0];
next.y+=to[i][1];
if(check(next.x,next.y))
continue;
next.step=a.step+1;
vis[next.x][next.y] = 1;
Q.push(next);
}
}
ans = -1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
int i,j;
for(i = 0; i<n; i++)
scanf("%s",map[i]);
for(i = 0; i<n; i++)
{
for(j = 0; j<m; j++)
{
if(map[i][j]=='S')
{
sx = i;
sy = j;
}
}
}
memset(vis,0,sizeof(vis));
bfs();
printf("%d\n",ans);
}
return 0;
}