constint N = 55; int t,n, m; int p[N][N]; // 存储是海洋还是岛屿 int vis[N][N]; // 岛屿是否访问过 int dx[] = { 0,0,-1,1,-1 ,-1,1,1}; int dy[] = { 1,-1,0,0,-1 ,1,-1,1}; // 我们从下标为 0 开始搜索
int ans = 0;
boolcheck(int x, int y){ if (x<0 || x>m+1 || y<0 || y>n+1) return0; return1; }
voiddfs(int x,int y){ vis[x][y] = 1; for (int i = 0; i < 4; i++) { int xx = x + dx[i], yy = y + dy[i]; if (p[xx][yy] == 1 && vis[xx][yy] == 0 && check(xx,yy)) { dfs(xx, yy); } } }
voiddfsfirst(int x, int y){ for (int i = 0; i < 8; i++) { int xx = x + dx[i], yy =y+ dy[i]; if (check(xx, yy) == 0) continue; if (p[xx][yy] == 0 && vis[xx][yy]!=-1) vis[xx][yy]=-1,dfsfirst(xx, yy); elseif (p[xx][yy] == 1 && vis[xx][yy]==0) { ans++; dfs(xx, yy); } } }
intmain(){ cin >> t; while (t--) { memset(p, 0, sizeof p), memset(vis, 0, sizeof vis),ans=0; cin >> m >> n; string s; for (int i = 1; i <= m; i++) { cin >> s; for (int j = 1; j <= n; j++) { p[i][j] = s[j-1]-'0'; } } dfsfirst(0, 0); cout << ans << endl; } }
constint N = 55; int t,n, m; int p[N][N]; // 存储是海洋还是岛屿 int vis[N][N]; // 岛屿是否访问过 int dx[] = { 0,0,-1,1,-1 ,-1,1,1}; int dy[] = { 1,-1,0,0,-1 ,1,-1,1}; // 我们从下标为 0 开始搜索
int ans = 0;
boolcheck(int x, int y){ if (x<0 || x>m+1 || y<0 || y>n+1) return0; return1; }
voidbfs(int x,int y){ queue<pair<int, int>> q; q.push({ x,y }); vis[x][y] = 1; while (q.size()) { int x = q.front().first, y = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int xx = x + dx[i], yy = y + dy[i]; if (check(xx, yy) == 0) continue; if (p[xx][yy] == 1 && vis[xx][yy] == 0) { vis[xx][yy] = 1; q.push({ xx,yy }); } } } }
voidbfsfirst(){ queue<pair<int, int>> q; q.push({ 0,0 }); while (q.size()) { int x = q.front().first, y = q.front().second; q.pop(); for (int i = 0; i < 8; i++) { int xx = x + dx[i], yy = y + dy[i]; if (check(xx, yy) == 0) continue; if (p[xx][yy] == 0 && vis[xx][yy] != -1) vis[xx][yy] = -1, q.push({ xx,yy }); elseif (p[xx][yy] == 1 && vis[xx][yy] == 0) ans++,bfs(xx, yy); } } }
intmain(){ cin >> t; while (t--) { memset(p, 0, sizeof p), memset(vis, 0, sizeof vis),ans=0; cin >> m >> n; string s; for (int i = 1; i <= m; i++) { cin >> s; for (int j = 1; j <= n; j++) { p[i][j] = s[j-1]-'0'; } } bfsfirst(); cout << ans << endl; } }