1416_深搜判环
深度优先搜索判断是否成环,代码如下,可以有O1优化空间。
#include<bits/stdc++.h> using namespace std; const long long MAXN=233; char mapp[MAXN][MAXN]; set<long long> s1; set<long long> s2; long long n,m; void init() { memset(mapp,0,sizeof(mapp)); cin>>n>>m; for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { cin>>mapp[i][j]; } } } bool dfs(int x,int y,int l1=MAXN,int l2=MAXN) { s1.insert(x*MAXN+y); if(s2.count(x*MAXN+y))return true; s2.insert(x*MAXN+y); char c=mapp[x][y]; if((x-1!=l1||y!=l2)&&x>0) { char a=mapp[x-1][y]; if(a==c&&dfs(x-1,y,x,y))return true; } if((x!=l1||y-1!=l2)&&y>0) { char a=mapp[x][y-1]; if(a==c&&dfs(x,y-1,x,y))return true; } if((x+1!=l1||y!=l2)) { char a=mapp[x+1][y]; if(a==c&&dfs(x+1,y,x,y))return true; } if((x!=l1||y+1!=l2)) { char a=mapp[x][y+1]; if(a==c&&dfs(x,y+1,x,y))return true; } return false; } void cal() { for(int i=0;i<n;++i) { for(int j=0;j<m;++j) { s2.clear(); if(!s1.count(i*MAXN+j)&&dfs(i,j)) { cout<<"Yes"<<endl; return; } } } cout<<"No"<<endl; } int main() { cin.sync_with_stdio(false); init(); cal(); return 0; }