深搜一次先找到,所有能到达的点,对所有的点进行再次深搜看能不能到达终点。记住能不能到达,加快搜索速度,90分,10分不知去向。。。。难受
#include<bits/stdc++.h>
using namespace std;
char a[55][55];
int visit[55][55]= {0},visit1[55][55],can[55][55];
int flag=0,cnt=0;
int n,m;
void dfs1(int u,int v,int k)
{
//if(flag==1)return;
if(a[u][v]=='#')
return;
if(a[u][v]=='T')
{
flag=1;//return ;
}
if(a[u][v]=='.')
{
if(u+1>n||a[u+1][v]=='#')
{
//cnt+=k;
return;
}
visit[u+1][v]=1;
dfs1(u+1,v,k+1);
}
if(a[u][v]=='S'||a[u][v]=='+'||a[u][v]=='T')
{
if(u>1&&!visit[u-1][v])
{
visit[u-1][v]=1;
dfs1(u-1,v,0);
}
if(u<n&&!visit[u+1][v])
{
visit[u+1][v]=1;
dfs1(u+1,v,0);
}
if(v>1&&!visit[u][v-1])
{
visit[u][v-1]=1;
dfs1(u,v-1,0);
}
if(v<m&&!visit[u][v+1])
{
visit[u][v+1]=1;
dfs1(u,v+1,0);
}
}
if(a[u][v]=='-')
{
if(v>1&&!visit[u][v-1])
{
visit[u][v-1]=1;
dfs1(u,v-1,0);
}
if(v<m&&!visit[u][v+1])
{
visit[u][v+1]=1;
dfs1(u,v+1,0);
}
}
if(a[u][v]=='|')
{
if(u>1&&!visit[u-1][v])
{
visit[u-1][v]=1;
dfs1(u-1,v,0);
}
if(u<n&&!visit[u+1][v])
{
visit[u+1][v]=1;
dfs1(u+1,v,0);
}
}
}
void dfs(int u,int v,int k)
{
if(flag==1)
return;
if(a[u][v]=='#')
return;
if(a[u][v]=='T'||can[u][v]==1)
{
flag=1;
return ;
}
if(a[u][v]=='.')
{
if(u+1>n||a[u+1][v]=='#')
{
//cnt+=k;
return;
}
visit[u+1][v]=1;
dfs(u+1,v,k+1);
}
if(a[u][v]=='S'||a[u][v]=='+'||a[u][v]=='T')
{
if(u>1&&!visit[u-1][v])
{
visit[u-1][v]=1;
dfs(u-1,v,0);
}
if(u<n&&!visit[u+1][v])
{
visit[u+1][v]=1;
dfs(u+1,v,0);
}
if(v>1&&!visit[u][v-1])
{
visit[u][v-1]=1;
dfs(u,v-1,0);
}
if(v<m&&!visit[u][v+1])
{
visit[u][v+1]=1;
dfs(u,v+1,0);
}
}
if(a[u][v]=='-')
{
if(v>1&&!visit[u][v-1])
{
visit[u][v-1]=1;
dfs(u,v-1,0);
}
if(v<m&&!visit[u][v+1])
{
visit[u][v+1]=1;
dfs(u,v+1,0);
}
}
if(a[u][v]=='|')
{
if(u>1&&!visit[u-1][v])
{
visit[u-1][v]=1;
dfs(u-1,v,0);
}
if(u<n&&!visit[u+1][v])
{
visit[u+1][v]=1;
dfs(u+1,v,0);
}
}
}
int main()
{
scanf("%d%d",&n,&m);
int u,v;
memset(can,0,sizeof(can));
for(int i=1; i<=n; i++)
{
getchar();
for(int j=1; j<=m; j++)
{
scanf("%c",&a[i][j]);
if(a[i][j]=='S')
{
u=i;
v=j;
}
}
}
visit[u][v]=1;
dfs1(u,v,0);
if(flag==0)
{
printf("I’m stuck!\n");
return 0;
}
can[u][v]=1;
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
visit1[i][j]=visit[i][j];
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
{
if(a[i][j]!='#'&&visit1[i][j])
{
memset(visit,0,sizeof(visit));
visit[i][j]=1;
flag=0;
dfs(i,j,0);
if(flag==0)
{
//printf("%d %d %c\n",i,j,a[i][j]);
cnt++;
}
if(flag==1)
can[i][j]=1;
}
}
cout<<cnt<<endl;
return 0;
}