标签:
好久好久,都没有写过搜索了,看了下最近在CF上有一道DFS水题 = =
数据量很小,爆搜一下也可以过
额外注意的就是防止往回搜索需要做一个判断。
Source code:
//#pragma comment(linker, "/STACK:16777216") //for c++ Compiler #include <bits/stdc++.h> #define Max(a,b) (((a) > (b)) ? (a) : (b)) #define Min(a,b) (((a) < (b)) ? (a) : (b)) #define Abs(x) (((x) > 0) ? (x) : (-(x))) #define MOD 1000000007 #define pi acos(-1.0) using namespace std; typedef long long ll ; typedef unsigned long long ull ; typedef unsigned int uint ; typedef unsigned char uchar ; template<class T> inline void checkmin(T &a,T b){if(a>b) a=b;} template<class T> inline void checkmax(T &a,T b){if(a<b) a=b;} const double eps = 1e-7 ; const int N = 1 ; const int M = 200000 ; const ll P = 10000000097ll ; const int INF = 0x3f3f3f3f ; char mp [80][80]; int n,m; int Dir [4][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int Vis [80][80]; int Fit(int x , int y){ return x >= 0 && x < n && y >= 0 && y < m; } int Dfs (int x, int y, int px, int py, char c){ Vis[x][y] = 1; for(int i = 0 ; i < 4 ; ++i){ int dx = x + Dir[i][0]; int dy = y + Dir[i][1]; if(dx == px && dy == py) continue; if (Fit (dx , dy) && mp[dx][dy] == c){ if (Vis[dx][dy]){ return 1; } if (Dfs (dx ,dy, x, y, mp[dx][dy])){ return 1; } } } return 0; } int main(){ int i ,j ; while(cin >> n >> m){ memset(Vis, 0, sizeof(Vis)); for(i = 0; i < n; ++i){ for(j = 0; j < m; ++j){ cin >> mp[i][j]; } } for(i = 0; i < n; ++i){ for(j = 0; j < m; ++j){ if(!Vis[i][j]){ if(Dfs(i, j, -1, -1, mp[i][j])){ cout << "Yes" << endl; return 0; } } } } cout << "No" << endl; } return 0; }
Codeforces 510B Fox And Two Dots 【DFS】
标签:
原文地址:http://www.cnblogs.com/wushuaiyi/p/4278149.html