版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_34524528/article/details/88023519
摘自: 算法笔记 8.2
BFS 模板
void BFS(int s){
queue<int> q;
q.push(s);
while(!q.empty()){
取出队首元素top;
访问队首元素top;
将队首元素出队;
将top下一层的结点中尚未访问的结点全部入队,并设置为已入队;
}
}
矩阵的块(数细胞)
Sample Input:
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
Sample Output:
4
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct node {
int x;
int y;
}Node;
int m, n;// 矩阵大小
const int maxn = 100;
int matrix[maxn][maxn];
int inq[maxn][maxn] = { false };//是否已经入过队
int X[4] = { 0,1,0,-1 };
int Y[4] = { -1,0,1,0 };//增量数组
bool judge(int newX, int newY) {
if (newX<0|| newX>=m||newY<0||newY>=n) {// 越界
return false;
}
if (matrix[newX][newY]==0 || inq[newX][newY] == true) {// 位置非1或已经入队
return false;
}
return true;
}
void BFS(int x, int y) {
queue<node> q;
Node.x = x, Node.y = y;
q.push(Node);
inq[x][y] = true;
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() {
scanf("%d%d", &n, &m);//n 为行数,m为列数
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf("%d", &matrix[i][j]);
}
}
int ans = 0;//块数
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (matrix[i][j] == 1 && inq[i][j] == false) {
ans++;
BFS(i, j);
}
}
}
printf("%d\n", ans);
return 0;
}
迷宫
Sample Input:
5 5
…
...
.S.
.**.
…T
Sample Output:
11
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
struct node {
int x, y;
int step;//步数(层数)
}S, T, Node;//起点、终点、临时点
int X[4] = { 0,1,0,-1 };
int Y[4] = { -1,0,1,0 };//四向
int n, m;//n行,m列
const int maxn = 100;
char maze[maxn][maxn];
bool inq[maxn][maxn] = { false };//是否已经入队
bool judge(int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m) { //越界
return 0;
}
if (maze[x][y] == '*') {// 墙
return false;
}
if (inq[x][y] == true) {//回头路
return false;
}
return true;
}
int BFS() {
queue<node> q;
q.push(S);
inq[S.x][S.y] = true;
while (!q.empty())
{
node top = q.front();
q.pop();
if (top.x == T.x && top.y == T.y) {
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() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++)
{
getchar();
for (int j = 0; j < m; j++)
{
maze[i][j] = getchar();
//记录起点、终点
if (maze[i][j] == 'S') {
S.x = i;
S.y = j;
}
if (maze[i][j] == 'T') {
T.x = i;
T.y = j;
}
}
}
S.step = 0;
printf("%d", BFS());
return 0;
}