题目链接:https://nanti.jisuanke.com/t/T1213
思路:BFS 遇到’x’的时候处理一下只是step+1;
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<cmath>
using namespace std;
const int MAXN = 200;
int visited[MAXN+10][MAXN+10];
struct Node
{
int x,y,step;
Node(int xx,int yy, int ss):x(xx),y(yy),step(ss){ }
};
queue<Node> q;
char room[220][220];
int dx[5]={-1,1,0,0};
int dy[5]={0,0,-1,1};
int n,m,qx,qy,zx,zy;
int main()
{
memset(visited,0,sizeof(visited));
cin >> n >> m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin >> room[i][j];
if(room[i][j]=='r'){
qx = i; qy = j;
}
else if(room[i][j]=='a'){
zx = i;zy = j;
}
}
}
q.push(Node(qx,qy,0));
while(!q.empty()){
Node s = q.front();
if(s.x==zx&&s.y==zy){
cout << s.step << endl;
return 0;
}
else {
if(room[s.x][s.y]=='x'){ // 关于x的处理在这 <<-----
room[s.x][s.y]='@';
q.push(Node(s.x,s.y,s.step+1)); // 只是步数+1
}
else{
for(int i=0;i<4;i++){
int xx = s.x + dx[i];
int yy = s.y + dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&!visited[xx][yy]&&room[xx][yy]!='#'){
visited[xx][yy]=1;
q.push(Node(xx,yy,s.step+1));
}
}
}
}
q.pop();
}
cout << "Impossible" << endl;
return 0;
}
用DFS会超时超时时时时
丑丑的贴上超时的代码:
我 / / 真 / / 菜 !!!
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
typedef long long ll;
int n,m,qx,qy,zx,zy;
char maze[220][220];
int step[220][220];
int dx[5]={0,0,-1,1};
int dy[5]={-1,1,0,0};
void dfs(int x,int y)
{
//cout <<step[x][y]<< "xxx****" << x << "yyy****" << y <<"***** "<<maze[x][y]<< endl;
if(x==zx&&y==zy) return ;
if(maze[x][y]=='@'&&step[x][y]+1>step[zx][zy]) return ;
else if(maze[x][y]=='x'&&step[x][y]+2>step[zx][zy]) return ;
for(int i=0;i<4;i++){
int xx = x + dx[i];
int yy = y + dy[i];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&maze[xx][yy]!='#'){
if(maze[xx][yy]=='x'&&step[x][y]+2<step[xx][yy]){
step[xx][yy] = step[x][y]+2;
dfs(xx,yy);
}
else if((maze[xx][yy]=='a'||maze[xx][yy]=='@')&&step[x][y]+1<step[xx][yy]){
step[xx][yy]=step[x][y]+1;
dfs(xx,yy);
}
}
}
}
int main()
{
cin >> n >> m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
step[i][j] = 1 << 30;
cin >> maze[i][j];
if(maze[i][j]=='r'){
qx = i; qy = j;
}
else if(maze[i][j]=='a'){
zx = i; zy = j;
}
}
}
step[qx][qy] = 0;
dfs(qx,qy);
if(step[zx][zy]==1 << 30)
cout << "Impossible";
else
cout << step[zx][zy];
return 0;
}