[CCF 201312-5] I’m stuck!
题面
Sample input
5 5
--+-+
..|#.
..|##
S-+-T
####.
Sample output
2
思路:
1. 从起点S开始做dfs, 记录所有起点可达的点(S,T除外)
2.对于每个起点可达的点,做dfs,如果无法到达T, 则答案数ans加一
代码:
/*
I'm stuck CCF 201312-5
2019/11/21 xzc 100
*/
#include <bits/stdc++.h>
using namespace std;
char a[60][60];
int Tx,Ty,Sx,Sy,r,c;
// 下 上 右 左
int dx[] = { 1,-1, 0, 0 };
int dy[] = { 0, 0, 1,-1 };
bool vis[60][60];
bool ok(int x,int y)
{
return (x>=0&&x<r&&y>=0&&y<c&&a[x][y]!='#'&&!vis[x][y]);
}
vector<pair<int,int> > V;
void dfs(int x,int y)
{
if(a[x][y]!='S'&&a[x][y]!='T') V.push_back(make_pair(x,y));
vis[x][y] = true;
int down = 0, up = 4;
if(a[x][y]=='-') down = 2, up = 4;
else if(a[x][y]=='|') down = 0, up = 2;
else if(a[x][y]=='.') down = 0, up = 1;
for(int i=down;i<up;++i)
{
int xx = x+dx[i], yy = y+dy[i];
if(!ok(xx,yy)) continue;
dfs(xx,yy);
}
}
void judge(int x,int y)
{
vis[x][y] = true;
if(vis[Tx][Ty]) return;
int down = 0, up = 4;
if(a[x][y]=='-') down = 2, up = 4;
else if(a[x][y]=='|') down = 0, up = 2;
else if(a[x][y]=='.') down = 0, up = 1;
for(int i=down;i<up;++i)
{
int xx = x+dx[i], yy = y+dy[i];
if(!ok(xx,yy)) continue;
dfs(xx,yy);
}
}
int main()
{
scanf("%d%d",&r,&c);
for(int i=0;i<r;++i)
{
scanf("%s",a[i]);
for(int j=0;j<c;++j)
{
if(a[i][j]=='S') Sx=i,Sy=j;
else if(a[i][j]=='T') Tx=i,Ty=j;
}
}
dfs(Sx,Sy);
if(!vis[Tx][Ty])
{
printf("I'm stuck!
");return 0;
}
int sz = V.size(),ans=0;
for(int i=0;i<sz;++i)
{
memset(vis,false,sizeof(vis));
judge(V[i].first,V[i].second);
if(!vis[Tx][Ty]) ++ans;
}
printf("%d
",ans);
return 0;
}
AK啦~