广度优先搜索小技巧
- 使用bool inq(in queue)来记录某一节点是不是入过队(而不是是否被访问)
矩阵的块 求给定的矩阵中块的个数
BFS解法
#include<queue>
#include<iostream>
using namespace std;
int X[] = { 0,0,1,-1 };
int Y[] = { 1,-1,0,0 };
const int max_x=30;
const int max_y=30;
bool inq[max_x][max_y] = { 0 };
int val[max_x][max_y];
struct point {
int x;
int y;
};
queue<point>q;
int x, y;
int cnt=0;
void BFS(int a,int b)
{
point* t = new point;
t->x = a;
t->y = b;
q.push(*t);
inq[a][b] = true;
point p;
while (!q.empty())
{
p = q.front();
q.pop();
//添加上下左右
if (val[p.x][p.y] == 1)
{
for (int i = 0; i < 4; i++)
{
int m = p.x + X[i], n = p.y + Y[i];
if (m >= 0 && m < x &&
n >= 0 && n < y)
{
if (!inq[m][n])
{
t = new point;
t->x = m;
t->y = n;
q.push(*t);
inq[m][n] = true;
}
}
}
}
}
}
int main()
{
scanf("%d%d", &x, &y);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
scanf("%d", &val[i][j]);
}
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (!inq[i][j])
{
if (val[i][j] == 1)
{
cnt++;
BFS(i,j);
}
}
}
}
printf("%d", cnt);
}
DFS解法
//求给定的矩阵中块的个数
#include<queue>
#include<iostream>
using namespace std;
int X[] = { 0,0,1,-1 };
int Y[] = { 1,-1,0,0 };
const int max_x=30;
const int max_y=30;
bool isvisited[max_x][max_y] = { 0 };
int val[max_x][max_y];
struct point {
int x;
int y;
};
queue<point>q;
int x, y;
int cnt=0;
void DFS(int a,int b)
{
isvisited[a][b] = true;
//如果上下左右是1,访问
for (int i = 0; i < 4; i++)
{
int m = a + X[i], n = b + Y[i];
if (m >= 0 && m < x &&
n >= 0 && n < y)
{
if (val[m][n] == 1)
{
if (!isvisited[m][n])
DFS(m, n);
}
}
}
}
int main()
{
scanf("%d%d", &x, &y);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
scanf("%d", &val[i][j]);
}
}
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (!isvisited[i][j])
{
if (val[i][j] == 1)
{
cnt++;
DFS(i, j);
}
}
}
}
printf("%d", cnt);
}