首先看下题目:
题目描述
给定一个N x M的01矩阵,其中1表示陆地,0表示水域。对于每一个位置,求出它距离最近的水域的距离是多少。
矩阵中每个位置与它上下左右相邻的格子距离为1。
输入
第一行包含两个整数,N和M。 以下N行每行M个0或者1,代表地图。 数据保证至少有1块水域。 1 <= N, M <= 100
输出
输出N行,每行M个空格分隔的整数。每个整数表示该位置距离最近的水域的距离。
样例输入
4 4
0110
1111
1111
0110
样例输出
0 1 1 0
1 2 2 1
1 2 2 1
0 1 1 0
通过分析可知可以采用BFS,先将0的点全部入队,然后通过BFS进行宽搜
我的代码如下:
#include<bits/stdc++.h>//包含C++的所有头文件
using namespace std;
const int maxn = 101;
typedef struct node{
int x;
int y;
int step;
}Node;
char maze[maxn][maxn];//存放 地图
int ans[maxn][maxn];//存放距离
bool inq[maxn][maxn]={false};//判断是否入队
//方位
int X[4] = {0,0,1,-1};
int Y[4] = {1,-1,0,0};
int n, m;
queue<Node> Q;
bool test(int x, int y){
//是否越界
if (x >= n || x < 0 || y >= m || y < 0){
return false;
}
//或者入队过
if (inq[x][y] == true){
return false;
}
return true;
}
void BFS(void){
Node c;
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];
c.x = newX;
c.y = newY;
c.step = top.step + 1;
if(test(newX, newY)){
ans[newX][newY] = top.step + 1;
Q.push(c);
inq[newX][newY] = true;
}
}
}
}
int main(){
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++){
for (int j = 0; j <m; j++){
cin >> maze[i][j];
}
}
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (maze[i][j] == '0'){
ans[i][j] = 0;
inq[i][j] = true;
Node node;
node.x = i;
node.y = j;
node.step = 0;
Q.push(node);
}
}
}
BFS();
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if (j == m - 1){
printf("%d\n", ans[i][j]);
}else{
printf("%d ", ans[i][j]);
}
}
}
return 0;
}
遇坑总结:
之前提交了几个代码一直报这个错误
然后观看了别人的题解,索性就把对地图的输入改成:
for (int i = 0; i < n; i++){
for (int j = 0; j <m; j++){
cin >> maze[i][j];
}
}
居然就AC了:
我之前写的是:
for (int i =0 ; i < n; i++){
getchar();//过滤后面的换行符
for (int j = 0; j < m; j++){
maze[i][j] = getchar();
}
maze[i][m +1] = '\0';
}
运行均没错,但是提交就只对33%,我也是很疑惑。
如果你遇到类似的问题,你可以参考参考。