标签:
题目链接:http://codeforces.com/problemset/problem/510/B
题目意思:给出 n 行 m 列只有大写字母组成的字符串。问具有相同字母的能否组成一个环。
很容易知道要用到深搜。暴力搜索~~~
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 using namespace std; 6 7 const int maxn = 50 + 5; 8 char g[maxn][maxn]; 9 bool vis[maxn][maxn]; 10 11 int dx[] = {0, 1, 0, -1}; 12 int dy[] = {1, 0, -1, 0}; 13 14 int n, m; 15 16 bool dfs(int x, int y, int px, int py, char c) 17 { 18 vis[x][y] = 1; 19 for (int i = 0; i < 4; i++) { 20 int tx = x + dx[i]; 21 int ty = y + dy[i]; 22 if (tx == px && ty == py) // 和上一次走过的点冲突 23 continue; 24 if (tx >= 0 && tx < n && ty >= 0 && ty < m && g[tx][ty] == c) { 25 if (vis[tx][ty]) // 形成环 26 return 1; 27 if (dfs(tx, ty, x, y, c)) 28 return 1; 29 } 30 } 31 return 0; 32 } 33 34 35 int main() 36 { 37 while (scanf("%d%d", &n, &m) != EOF) { 38 for (int i = 0; i < n; i++) 39 scanf("%s", g[i]); 40 memset(vis, 0, sizeof(vis)); 41 42 bool flag = false; 43 for (int i = 0; i < n && !flag; i++) { 44 for (int j = 0; j < m && !flag; j++) { 45 if (!vis[i][j]) { 46 if (dfs(i, j, -1, -1, g[i][j])) { 47 flag = true; 48 break; 49 } 50 } 51 } 52 } 53 printf("%s\n", flag ? "Yes" : "No"); 54 } 55 return 0; 56 }
cgy4ever 的代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 int n, m; 5 string board[51]; 6 bool visited[51][51]; 7 bool findCycle = false; 8 int dx[] = {1, -1, 0, 0}; 9 int dy[] = {0, 0, 1, -1}; 10 11 void dfs(int x, int y, int fromX, int fromY, char needColor) 12 { 13 if(x < 0 || x >= n || y < 0 || y >= m) return; 14 if(board[x][y] != needColor) return; 15 if(visited[x][y]) 16 { 17 findCycle = true; 18 return; 19 } 20 visited[x][y] = true; 21 for(int f = 0; f < 4; f++) 22 { 23 int nextX = x + dx[f]; 24 int nextY = y + dy[f]; 25 if(nextX == fromX && nextY == fromY) continue; 26 dfs(nextX, nextY, x, y, needColor); 27 } 28 } 29 30 int MAIN() 31 { 32 cin >> n >> m; 33 for(int i = 0; i < n; i++) 34 cin >> board[i]; 35 memset(visited, false, sizeof(visited)); 36 for(int i = 0; i < n; i++) 37 for(int j = 0; j < m; j++) 38 if(!visited[i][j]) 39 dfs(i, j, -1, -1, board[i][j]); 40 cout << (findCycle ? "Yes" : "No") << endl; 41 return 0; 42 } 43 44 int main() 45 { 46 #ifdef LOCAL_TEST 47 freopen("in.txt", "r", stdin); 48 freopen("out.txt", "w", stdout); 49 #endif 50 ios :: sync_with_stdio(false); 51 cout << fixed << setprecision(16); 52 return MAIN(); 53 }
codeforces 510B. Fox And Two Dots 解题报告
标签:
原文地址:http://www.cnblogs.com/windysai/p/4293748.html