最近很忙,虽然我知道只给代码,不写注释很恶心,但是真的没时间写。。。不好意思呀
给点提示,结构体中的state有三个值:
1表示可以通过S访问到
2表示可以访问到T
3表示两者都可以访问到,这样设计是因为3=2&1
#include<stdio.h>
#include <map>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int n,m,sx,sy,tx,ty;
struct Node{
Node(int x_,int y_,char op_){
x=x_,y=y_,op=op_;
}
int x,y;
bool vis=false;
int state=0;
char op;
};
vector< vector<Node> > M;
int DFS(int x,int y,int &res,bool flag){
if(x>=n || x<0 || y>=m || y<0) return 0;
if(M[x][y].op=='#'){
return 0;
}
if(M[x][y].vis) return M[x][y].state;
if(flag) M[x][y].state|=1;
M[x][y].vis=true;
if(x==tx && y==ty){
M[x][y].state|=2;
}
if(M[x][y].op=='+' || M[x][y].op=='S' || M[x][y].op=='T'){
M[x][y].state |=DFS(x-1,y,res,flag)&2;
M[x][y].state |=DFS(x+1,y,res,flag)&2;
M[x][y].state |=DFS(x,y+1,res,flag)&2;
M[x][y].state |=DFS(x,y-1,res,flag)&2;
}
else if(M[x][y].op=='-'){
M[x][y].state |=DFS(x,y+1,res,flag)&2;
M[x][y].state |=DFS(x,y-1,res,flag)&2;
}
else if(M[x][y].op=='|'){
M[x][y].state |=DFS(x+1,y,res,flag)&2;
M[x][y].state |=DFS(x-1,y,res,flag)&2;
}
else if(M[x][y].op=='.'){
M[x][y].state |=DFS(x+1,y,res,flag)&2;
}
if(M[x][y].state==1) res++;
return M[x][y].state;
}
int main(){
cin >> n >> m;
char op;
for(int i=0;i<n;i++){
vector<Node> tmp;
for(int j=0;j<m;j++){
cin >> op;
if(op=='S') sx=i,sy=j;
else if(op=='T') tx=i,ty=j;
tmp.push_back(Node(i,j,op));
}
M.push_back(tmp);
}
int ans=0;
M[sx][sy].state|=1;
DFS(sx,sy,ans,true);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
DFS(i,j,ans,false);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
M[i][j].vis=false;
}
}
ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(M[i][j].state==1) ans++;
}
}
if(M[sx][sy].state==1) cout << "I'm stuck!";
else cout << ans;
return 0;
}