有关入队、出队顺序,是否把节点加入队列状态的判断
0-1边权的 B F S BFS BFS,节点可以多次入队,因为可能被插入队头,也可能被插入到队尾,所以节点可以多次入队。因此 v i s vis vis数组(记录节点是否被访问过)的判断不能写在for循环里面。当节点第一次出队的时候,所得的路径长度是最短路径长度。for循环里面的更新类似于 d i j k s t r a dijkstra dijkstra等最短路算法的更新方式,只有当更新后路径比以前更小才更新。因为d数组可以是全局数组。
示例代码
题目来源:洛谷P4667 [BalticOI 2011 Day1]Switch the Lamp On
AC代码
#include<cstdio>
#include<queue>
#include<deque>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn = 510;
char s[maxn][maxn];
struct rec{
int x, y;
};
int n, m;
int d[maxn][maxn];
bool vis[maxn][maxn];
int dx[4] = {
-1, 1, -1, 1};
int dy[4] = {
-1, 1, 1, -1};
deque<rec> q;
void init()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n;i++)
{
cin >> (s[i] + 1);
}
if((n&1)!=(m&1))
printf("NO SOLUTION\n");
for (int i = 1; i <= n+1;i++)
for (int j = 1; j <= m+1;j++)
d[i][j] = -1;
}
bool valid(int x,int y)
{
return x >= 1 && y >= 1 && x <= n + 1 && y <= m + 1;
}
void bfs(int a,int b)
{
rec st;
st.x = a, st.y = b;
d[a][b] = 0;
q.push_back(st);
while (!q.empty())
{
rec now = q.front();
q.pop_front();
rec next;
if(d[n+1][m+1]!=-1){
printf("%d\n",d[n+1][m+1]);
return;
}
if(vis[now.x][