真的stuck了!为什么只有80分 求大佬解答
写的繁琐点了
#include<iostream>
#include<string>
#include<stack>
#include<cstdio>
using namespace std;
char a[200][200];
int visit[200][200];
int visit1[200][200];
int r,c;
int dx[4]={-1,0,0,1};
int dy[4]={0,1,-1,0};
int leftright[2]={-1,1};
int updown[2]={-1,1};
struct Node
{
int x,y;
char ch;
};
void BFS(int k,int j)
{
int xx,yy;
visit[k][j]=1;
Node t;
Node t1;
stack<Node> s;
t.x=k;
t.y=j;
t.ch='S';
s.push(t);
int i;
while(!s.empty())
{
t=s.top();
s.pop();
if(t.ch=='S'||t.ch=='T'||t.ch=='+')
{
for(i=0;i<4;i++)
{
xx=t.x+dx[i];
yy=t.y+dy[i];
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit[xx][yy]=1;
}
}
else if(t.ch=='-')
{
for(i=0;i<2;i++)
{
xx=t.x;
yy=t.y+leftright[i];
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit[xx][yy]=1;
}
}
else if(t.ch=='|')
{
for(i=0;i<2;i++)
{
xx=t.x+updown[i];
yy=t.y;
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit[xx][yy]=1;
}
}
else if(t.ch=='.')
{
xx=t.x+1;
yy=t.y;
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit[xx][yy]=1;
}
}
}
void initial()
{
int i,j;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
visit1[i][j]=0;
}
void BFS1(int k,int j)
{
int xx,yy;
visit1[k][j]=1;
Node t;
Node t1;
int i;
stack<Node> s;
t.x=k;
t.y=j;
t.ch=a[k][j];
s.push(t);
while(!s.empty())
{
t=s.top();
s.pop();
if(t.ch=='S'||t.ch=='T'||t.ch=='+')
{
for(i=0;i<4;i++)
{
xx=t.x+dx[i];
yy=t.y+dy[i];
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit1[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit1[xx][yy]=1;
}
}
else if(t.ch=='-')
{
for(i=0;i<2;i++)
{
xx=t.x;
yy=t.y+leftright[i];
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit1[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit1[xx][yy]=1;
}
}
else if(t.ch=='|')
{
for(i=0;i<2;i++)
{
xx=t.x+updown[i];
yy=t.y;
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit1[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit1[xx][yy]=1;
}
}
else if(t.ch=='.')
{
xx=t.x+1;
yy=t.y;
if(xx<0||xx>=r||yy<0||yy>=c)
continue;
if(visit1[xx][yy]==1)
continue;
if(a[xx][yy]=='#')
continue;
t1.x=xx;
t1.y=yy;
t1.ch=a[xx][yy];
s.push(t1);
visit1[xx][yy]=1;
}
}
}
int main()
{
cin>>r>>c;
int i,j;
int x,y;
for(i=0;i<r;i++)
scanf("%s",a[i]);
for(i=0; i<r; i++)
for(j=0; j<c; j++)
{
if(a[i][j]=='S')
{
BFS(i,j);
}
else if(a[i][j]=='T')
{
x=i;
y=j;
}
}
if(visit[x][y]==1)
{
int cnt=0;
for(i=0;i<r;i++)
for(j=0;j<r;j++)
{
if(visit[i][j]==1)
{
initial();
BFS1(i,j);
if(visit1[x][y]==0)
cnt++;
}
}
cout<<cnt<<endl;
}
else cout << "I'm stuck!" << endl;
return 0;
}