洛谷 P1162 填塗顏色 DFS
阿新 • • 發佈:2022-03-31
P1162 填塗顏色
https://www.luogu.com.cn/problem/P1162
qaq搜尋好抽象啊,蒟蒻表示難以理解,搞半天才做出來一道題,很挫敗www
思路
染色法。找牆壁外的連通塊0,染成新顏色。
注意邊界問題:為了照顧到邊緣的連通塊,我們的範圍要設定為0 ~ n + 1
程式碼
#include <iostream> #include <algorithm> #include <queue> using namespace std; const int N = 35; int n; int a[N][N], b[N][N]; int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0}; bool vis[N][N]; void dfs (int x, int y) { for (int i = 0; i < 4; i ++) { int xx = x + dx[i], yy = y + dy[i]; if (xx > n + 1 || xx < 0 || yy > n + 1 || yy < 0 || a[xx][yy]) //這個邊界很玄幻啊 continue; a[xx][yy] = 3; dfs (xx, yy); } } int main(){ cin >> n; for (int i = 1; i <= n; i ++) for (int j = 1; j <= n; j ++) cin >> a[i][j]; dfs (1, 1); for (int i = 1; i <= n; i ++){ for (int j = 1; j <= n; j ++) { if (a[i][j] == 0) cout << 2 << ' '; else if (a[i][j] == 3) cout << 0 << ' '; else cout << 1 << ' '; } cout << endl; } } //找牆外聯通塊