CF510B Fox And Two Dots
阿新 • • 發佈:2020-08-29
題目大意
矩陣中各個方格都有顏色,判斷是否有相同顏色的方塊可以組成環。(原題連結:CF510B Fox And Two Dots)
輸入:
第一行:\(n\), \(m\),表示矩陣的行和列
接下來\(n\)行: 輸入矩陣
輸出:
如果有環則輸出:\(Yes\), 否則輸出:\(No\);
樣例:
輸入樣例:\(*1\)
3 4
AAAA
ABCA
AAAA
輸出樣例: \(*1\)
Yes
輸入樣例:\(*2\)
3 4
AAAA
ABCA
AADA
輸出樣例: \(*2\)
No
思路:
其實就是判斷連通塊,然後再加個條件能否搜到初始點。
不過要注意的是:
1.不能搜當前點的上一個狀態,即用兩個變數記錄一下即可,如果是就\(continue\) 即可
剩下的就是常規\(dfs\)了,還有就是可以提前記錄一下每個字母的數量,如果小於\(4\)那麼可以直接不用搜了。
程式碼:
#include <iostream> using namespace std; const int N = 55; int n, m; char g[N][N]; bool st[N][N], flag; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; int cnt[27]; void dfs(int x, int y, char temp, int lastX, int lastY) { st[x][y] = true; for(int i = 0; i < 4; i++) { int xx = x + dx[i], yy = y + dy[i]; if(xx == lastX && yy == lastY) continue; //上個點 if(st[xx][yy] && g[xx][yy] == temp) flag = 1; //說明搜到 if(xx >= 1 && xx <= n && yy >= 1 && yy <= m && g[xx][yy] == temp && !st[xx][yy]) dfs(xx, yy, temp, x, y); } return; } int main() { cin >> n >> m; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { cin >> g[i][j]; cnt[g[i][j] - 'A']++; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(!st[i][j] && cnt[g[i][j] - 'A'] >= 4) dfs(i, j, g[i][j], 0, 0); if(flag == 1) { cout << "Yes" << endl; return 0; } } } if(!flag) cout << "No" << endl; return 0; }