例1:
基本思想:枚举每一个位置的元素,如果为0,则跳过;如果为1,则使用BFS查询与该位置相邻的4个位置,判断它们是否为1(如果某个相邻的位置为1,则同样去查询与该位置相邻的4个位置,指导整个“1”块访问完毕)。为了防止走回头路,一般可以设置一个bool型数组inq(即in queue的简写)来记录每个位置是否在BFS中已入过队。
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 100;
int n, m;
int matrix[maxn][maxn];
bool inq[maxn][maxn] = {false};
int X[4] = {0, 0, 1, -1};
int Y[4] = {1, -1, 0, 0};
struct node{
int x, y;
}Node;
bool judge(int x, int y){//判断该点是否需要访问
if(x < 0 || x >= n || y < 0 || y >= m)
return false;
if(matrix[x][y] == 0 || inq[x][y] == true)
return false;
return true;
}
void BFS(int x, int y){
queue<node> Q;
Node.x = x, Node.y = y;
Q.push(Node);
while(!Q.empty()){
node top = Q.front();
Q.pop();
for(int i = 0; i < 4; i++){
int newX = top.x + X[i];
int newY = top.y + Y[i];
if(judge(newX, newY)){
Node.x = newX, Node.y = newY;
Q.push(Node);
inq[newX][newY] = true;
}
}
}
}
int main(){
cin >> n >> m;//输入矩阵的行,列 m*n
int i, j;
for(i = 0; i < n; i++)//n.m的位置容易搞混,行在内层循环
for(j = 0; j < m; j++)
cin >> matrix[i][j];
int ans = 0;
for(i = 0; i < n; i++)
for(j = 0; j < m; j++)
{
if(inq[i][j] == false && matrix[i][j] == 1)
{
ans++;
BFS(i, j);
}
}
cout << ans;
}
例2:
Note:
本题中特别注意统计层数的地方,层数step不能设置成全局变量或和函数内变量,必须包含在遍历的每个点中。
inq数组的含义是判断结点是否已入过队,而不是结点是否已被访问。
输入:
5 5
. . . . .
. * . * .
. * . * .
. * * * .
. . . . *
输出:
11
代码:
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 100;
int m, n;
bool inq[maxn][maxn] = {false};//此路之前有无走过
char matrix[maxn][maxn];//星点矩阵
int X[4] = {0, 0, 1, -1};
int Y[4] = {1, -1, 0, 0};
struct node{
int x, y;
int step = 0;
}Node;
//判断此路可行
bool judge(int x, int y){
if(x >= n || x < 0 || y >= m || y < 0)
return false;
if(matrix[x][y] == '*' || inq[x][y] == true)
return false;
return true;
}
int BFS(int x1, int y1, int x2, int y2){
Node.x = x1, Node.y = y1;
queue<node> Q;
Q.push(Node);//将起点入队
while(!Q.empty()){
node top = Q.front();
Q.pop();
if(top.x == x2 && top.y == y2)//是终点,返回
return top.step;
for(int i = 0; i < 4; i++)
{
int newX = top.x + X[i];
int newY = top.y + Y[i];
if(judge(newX, newY)){
Node.x = newX, Node.y = newY;
Node.step = top.step + 1;
Q.push(Node);
inq[newX][newY] = true;
}
}
}
return -1;
}
int main(){
int i, j;
cin >> m >> n;
for(i = 0; i < m; i++)//输入星点矩阵迷宫
for(j = 0; j < n; j++)
cin >> matrix[i][j];
int x1, y1, x2, y2;//输入起,终点坐标
cin >> x1 >> y1 >> x2 >> y2;
cout << BFS(x1, y1, x2, y2);//输出步数
}