本地测试没有问题,怀疑是哪里越界了
#include <iostream>
using namespace std;
/**
* 联通块问题
* 用dfs打标记
*/
const int N = 110;
char map[N][N];
bool st[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int n, m, cnt;
void dfs(int x, int y){
if(st[x][y]) return;
st[x][y] = true;
// 往四个方向搜索
for(int i = 0; i < 4; ++ i){
int tx = x + dx[i], ty = y + dy[i];
if(tx > 0 && tx <= n && ty > 0 && ty <= m
&& !st[tx][ty] && map[tx][ty] == '1')
dfs(tx, ty);
}
}
int main(){
ios::sync_with_stdio(false);
cin >> n >> m;
char c;
for(int i = 1; i <= n;){
int j = 1;
while((c = getchar()) != '\n' && c != '\r'){
map[i][j ++] = c == '0' ? '0' : '1';
}
i ++;
}
for(int i = 1; i <= n; ++ i){
for(int j = 1; j <= m; ++ j){
if(!st[i][j] && map[i][j] == '1'){
cnt ++;
// 标记连通块
dfs(i, j);
}
}
}
cout << cnt;
return 0;
}