P1162 填塗顏色題解
阿新 • • 發佈:2021-07-28
理解與感悟
1、從邊緣出發進行思考。
2、把外圍所有0塗色幹掉,再剩下的0就是被包裹住的0,這些0需要修改為2.
3、所以OI的競賽題,幾乎沒有祼的模板題,都是需要一點點思維難度的。這需要進行訓練,刷題,沒有別的辦法。
#include <bits/stdc++.h> using namespace std; const int N = 40; int n; int a[N][N]; int b[N][N]; int dx[] = {0, 0, -1, 1}; int dy[] = {-1, 1, 0, 0}; struct coord { int x, y; }; //廣度優先搜尋 void bfs(int x, int y) { queue<coord> q; q.push({x, y}); while (!q.empty()) { coord p = q.front(); q.pop(); b[p.x][p.y] = -1; for (int i = 0; i < 4; i++) { int x1 = p.x + dx[i], y1 = p.y + dy[i]; if (b[x1][y1] >= 0 && x1 >= 1 && x1 <= n && y1 >= 1 && y1 <= n && a[x1][y1] == 0) { q.push({x1, y1}); b[x1][y1] = -1; } } } } int main() { //讀入地圖 cin >> n; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { cin >> a[i][j]; b[i][j] = a[i][j]; } //思路:從邊緣(四條外邊),找0,然後BFS找出所有區域,這些區域就是不被圈起來的範圍,進行標識,再取反 for (int i = 1; i <= n; i++) if (a[1][i] == 0) bfs(1, i); //第一行 for (int i = 1; i <= n; i++) if (a[i][1] == 0) bfs(i, 1); //第一列 for (int i = 1; i <= n; i++) if (a[n][i] == 0) bfs(n, i); //最後一行 for (int i = 1; i <= n; i++) if (a[i][n] == 0) bfs(i, n); //最後一列 //輸出 for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (b[i][j] == -1) cout << 0 << " "; else if (b[i][j] == 0) cout << 2 << " "; else cout << b[i][j] << " "; } cout << endl; } return 0; }