地址:
点击打开链接
这个题有两种思路,我注释在代码里了,但是这两种思路只是同一种方法的不同实现,都是DFS。
#include <iostream>
#include <iomanip>
#include<queue>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<iomanip>
#include<string.h>
#include<sstream>
#include<string>
#include<queue>
using namespace std ;
const int MAX=25 ;
int Vis[MAX][MAX][2];
char Map[MAX][MAX];
int col,row ;
int d[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
struct Node{
int x,y,time;
};
bool inMap(int x,int y )
{
if(x<0||x>=row||y<0||y>=col )
{
return false ;
}
return true ;
}
//这个题有两种思路,就是会无限迭代。一个是不断迭代,直到为空,每次找最小值,返回最小值,另一种就是下面写的这种,不断迭代,直到知道第一次到达终点为止。
int DFS(int startX,int startY)
{
Node first ;
first.x = startX;
first.y = startY;
first.time = 0 ;
std::queue<Node> q ;
q.push(first);
while(!q.empty())
{
Node now ,next ;
now = q.front();
q.pop();
// cout <<now.x <<" "<< now.y <<endl;
if(Map[now.x][now.y]=='T')
{
return now.time;
}
int nextX,nextY;
int x , y ;
x = now.x;
y = now.y;
for(int i = 0 ; i < 4 ; i ++)
{
nextX = now.x+d[i][0];
nextY = now.y+d[i][1];
int flag = 0 ;
if(!inMap(nextX,nextY))
{
continue;
}
if(Map[nextX][nextY]=='*')
{
continue ;
}else if(Vis[nextX][nextY][now.time%2]==1)
{
continue ;
}
if(Map[nextX][nextY]=='|')
{
if(now.time%2==1&&(i==2||i==3))
{
//将这个桥的状态标记为已读
Vis[nextX][nextY][now.time%2]= 1 ;
nextX +=d[i][0];
nextY +=d[i][1];
}else if(now.time%2==0&&(i==1||i==0))
{
//将这个桥的状态标记为已读
Vis[nextX][nextY][now.time%2] = 1 ;
nextX +=d[i][0];
nextY +=d[i][1];
}else {
Node t = now ;
t .time ++ ;
q.push(t);
continue ;
}
}else if(Map[nextX][nextY]=='-')
{
if(now.time%2==0&&(i==2||i==3))
{
//将这个桥的状态标记为已读
Vis[nextX][nextY][now.time%2] = 1 ;
nextX +=d[i][0];
nextY +=d[i][1];
}else if(now.time%2==1&&(i==1||i==0)){
//将这个桥的状态标记为已读
Vis[nextX][nextY][now.time%2] = 1 ;
nextX +=d[i][0];
nextY +=d[i][1];
}
else {
Node t = now ;
t .time ++ ;
q.push(t);
continue ;
}
}
if(!inMap(nextX,nextY))
{
continue;
}
else if(Map[nextX][nextY]=='*')
{
continue ;
}else if(Vis[nextX][nextY][now.time%2])
{
continue ;
}
//开出第三维的目的是为了,标记桥的状态,因此不是楼梯的话,直接访问过后,就把两个状态都设置成走过即可
Vis[nextX][nextY][now.time%2] = 1 ;
Vis[nextX][nextY][(now.time+1)%2] = 1 ;
Node temp = now ;
temp.x = nextX;
temp.y = nextY;
temp.time = now.time +1 ;
q.push(temp);
}
}
}
int main()
{
while(std::cin>>row>>col)
{
int flag = 0 ,startX,startY;
memset(Vis,0,sizeof(Vis));
for(int i = 0 ; i < row ; i ++)
{
for(int j = 0 ; j < col ;j++)
{
std::cin>>Map[i][j];
if(Map[i][j]=='S')
{
startX = i ;
startY = j;
}
}
}
Map[startX][startY]=1 ;
cout << DFS(startX,startY)<< endl;
}
return 0;
}