蓝桥OJ 178全球变暖
思路:
将每一座岛屿用一个颜色scc代替, 用dx[]和dy[]判断他的上下左右是否需要标记颜色,如果已经标记过颜色或者是海洋就跳过.后面的淹没,实际上就是哪个块上下左右有陆地,那么就不会被淹没,我用一个tag标记,如果上下左右一旦有海洋,tag就变为false.如果tag为true的话,就用一个vis数组判断是否为同一块岛屿,如果岛屿前面没有出现过就ans++,此ans代表没有被完全淹没的岛屿,题目问完全淹没的岛屿有多少,即scc-ans为答案
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
int n, col[N][N], ans, scc;
bool vis[N*N];
char a[N][N];int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};void dfs(int x, int y)
{col[x][y] = scc;for (int k = 0; k < 4; k++){int nx = x + dx[k],ny = y + dy[k];if (col[nx][ny] || a[nx][ny] == '.') continue;dfs(nx,ny);}
}
int main()
{cin >> n;for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){cin >> a[i][j];}}for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){if (col[i][j] || a[i][j] == '.') continue;scc++;dfs(i,j);}}//淹没后for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){bool tag = true;for (int k = 0; k < 4; k++){int x = i + dx[k],y = j + dy[k];if (a[x][y] == '.') tag = false;}if (tag){if (!vis[col[i][j]]) ans++;vis[col[i][j]] = true;}}}cout << scc - ans << '\n';return 0;
}