问题
BFS算法结果错误,目前水平太菜,检查多遍没有发现异常,Debug结果发现“块”的边界没有置0
求大佬指点,不胜感激~
题目描述
给出一个 mxn 的矩阵,矩阵中的元素为0或1。称位置(x,y)与其上下左右四个位置(x,y+1)、(x,y-1)、(x+1,y)、(x-1,y)是相邻的。如果矩阵中有若干个1是相邻的(不必两两相邻),那么称这些1构成了一个“块”。求给定的矩阵中“块”的个数。
输入用例
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
1 1 1 1 0 0 0
输出用例
4
解决代码
DFS没问题,但是BFS有问题
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 100;
struct Point
{
int x, y;
Point() {}
Point(int _x, int _y)
{
x = _x;
y = _y;
}
};
int m = 7, n = 7, count = 0;
int matrix[maxn][maxn] = {
{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},
{1, 1, 1, 1, 0, 0, 0},
};
int xp[4] = {1, 0, -1, 0};//横坐标
int yp[4] = {0, -1, 0, 1};//纵坐标
void DFS(int x, int y) // DFS访问块,将访问过的点置0
{
//递归边界
if (x < 0 || y < 0 || x >= m || y >= n || matrix[x][y] == 0)
return;
//右->下->左->上
matrix[x][y] = 0; //访问的元素是1,置为0
for (int i = 0; i < 4; i++)
DFS(x + yp[i], y + xp[i]);
}
void BFS(int x, int y) // BFS访问块,将访问过的点置0
{
int i;
Point point = Point(x, y);
queue<Point> q;
q.push(point);
matrix[x][y] = 0;
while (!q.empty())
{
q.pop();
//右->下->左->上
for (i = 0; i < 4; i++)
{
point.x = 0;
point.y = 0;
point.x = x + yp[i];
point.y = y + xp[i];
if (point.x < 0 || point.y < 0 || point.x >= m || point.y >= m || matrix[point.x][point.y] == 0)
continue;
matrix[point.x][point.y] = 0;
q.push(point);
}
}
}
int main()
{
int i, j;
// cin >> m >> n;
// for (i = 0; i < 7; i++)
// {
// for (j = 0; j < 7; j++)
// cout << matrix[i][j] << " ";
// cout << "\n";
// }
// cout << "--------------------\n";
// for (i = 0; i < m; i++)
// {
// for (j = 0; j < n; j++)
// cin >> matrix[i][j];
// }
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (matrix[i][j] == 1)
{
// DFS(i, j);
BFS(i, j);
count++;
}
}
}
cout << count;
return 0;
}