迷宫
起点到终点是否联通
#include<bits/stdc++.h>
using namespace std;
#define fast(); ios::sync_with_stdio(false);cin,tie(0),cout.tie(0);
typedef long long ll;
typedef pair<int,int> PII;
const int N=105;
int n;
char w[N][N];
PII st,ed;
bool vis[N][N];
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
bool dfs(int x,int y){
if(x==ed.first&&y==ed.second) return true;
vis[x][y]=true;
for(int i=0;i<4;i++){
int nx=x+dx[i],ny=y+dy[i];
if(nx<1||ny<1||nx>n||ny>n) continue;
if(w[nx][ny]=='#') continue;
if(vis[nx][ny]) continue;
if(dfs(nx,ny)) return true;
}
return false;
}
int main(){
int t;cin>>t;
while(t--){
cin>>n;
for(int i=1;i<=n;i++){
cin>>w[i]+1;
}
int a,b,c,d;cin>>a>>b>>c>>d;
st={a+1,b+1};ed={c+1,d+1};
if(w[st.first][st.second]=='#'||w[ed.first][ed.second]=='#'){
cout<<"NO"<<endl;
continue;
}
memset(vis,false,sizeof vis);
if(dfs(st.first,st.second)) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
红与黑
连通块大小
#include<iostream>
#include<cstring>
using namespace std;
const int N=25;
int n,m;
char a[N][N];
bool vis[N][N];
int nx[]={0,0,-1,1};
int ny[]={1,-1,0,0};
int dfs(int x,int y)
{
int cnt=1;
vis[x][y]=true;
for(int i=0;i<4;i++){
int dx=x+nx[i],dy=y+ny[i];
if(dx<1||dy<1||dx>n||dy>m) continue;
if(vis[dx][dy]) continue;
if(a[dx][dy]!='.') continue;
cnt+=dfs(dx,dy);
}
return cnt;
}
int main()
{
while(cin>>m>>n&&m&&n)
{
memset(vis,0,sizeof vis);
int x,y;
for(int i=1;i<=n;i++) cin>>a[i]+1;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(a[i][j]=='@')
{
x=i,y=j;break;
}
cout<<dfs(x,y)<<endl;
}
}