HDU T1180 诡异的楼梯

版权声明:希望能帮到弱校的ACMer成长,因为自己是弱校菜鸡~~~~ https://blog.csdn.net/Mr__Charles/article/details/82184986

                          HDU T1180 诡异的楼梯


题解:

    一开始倒没被题目的变化吓住,但却写代码走火入魔了,没实现分析好可能的情况,导致了花了大把时间,还是太菜了......

    看了下其他人的写法,有直接Bfs的,也有说Bfs+优先队列的。这里,鄙人很负责的告诉你,优先队列用不用无所谓。

    举个栗子:

    ****|
    **##*
    **##*
    *S***
    *****

    (鄙人比较懒,就不一一对齐了,大家可以复制出来看)

    从S到达桥有两条路,路径长度一样,但是总有一条路是不能通过桥的(因为桥是单向的)

    被桥堵住的路,它所花费的时间需要+1之后才能通过桥,也就是在桥旁等一等(对,你没听错,还可以等桥变换之后再走)

    可以走过桥的路,肯定比被桥堵住的路所花费的时间少,在这里是少1(因为题目中说过桥花费的时间也是1)。

    综上,可以走过桥的路 , 肯定是比  ,被桥堵住的路 ,  先出队列。

    所以,用不用优先队列无所谓。

 

代码:

#include<cstdio>
#include<iostream>
#include<queue>
#define maxn 25
using namespace std;

int n,m,mov[4][2] = {-1,0,0,1,1,0,0,-1};
char maps[maxn][maxn];
bool vis[maxn][maxn];

struct Node{
	int x,y,st;
}now,nex;

bool charge(int x,int y){
	if(x > n-1 || x < 0 || y > m-1 || y < 0 || maps[x][y] == '*' || vis[x][y] == true)
	    return false;
	return true;
}

int Bfs(int x,int y,int st){
	now.x = x;
	now.y = y;
	now.st = st;
	vis[x][y] = true;
	queue<Node> Q;
	Q.push(now);
	while(!Q.empty()){
		now = Q.front();
		Q.pop();
		if(maps[now.x][now.y] == 'T')
		    return now.st;
		int k = now.st & 1;
		for(int i = 0; i < 4; ++i){
			nex.x = now.x + mov[i][0];
			nex.y = now.y + mov[i][1];
			if(charge(nex.x,nex.y)){
				if(maps[nex.x][nex.y] == '|' || maps[nex.x][nex.y] == '-'){
					char bridge;
					if(k){
						if(maps[nex.x][nex.y] == '|')
						    bridge = '-';
						else 
						    bridge = '|';
					}
					else bridge = maps[nex.x][nex.y];
					
					if((bridge == '|' && (i == 1 || i == 3)) || ((bridge == '-') && (i == 0 || i == 2))){
						nex.x -= mov[i][0];
						nex.y -= mov[i][1];
						nex.st = now.st + 1;
						Q.push(nex);
					}
					else{
						nex.x += mov[i][0];
						nex.y += mov[i][1];
						if(charge(nex.x,nex.y)){
							vis[nex.x][nex.y] = true;
							nex.st = now.st + 1;
							Q.push(nex);
						}
					}
				}
				else{
					vis[nex.x][nex.y] = true;
					nex.st = now.st + 1;
					Q.push(nex);
				}
			}
		}
	}
}


int main(){
	int x,y;
	while(~scanf("%d%d",&n,&m)){
		for(int i = 0; i < n; ++i){
			scanf("%s",&maps[i]);
			for(int j = 0; j < m; ++j){
			    if(maps[i][j] == 'S'){
			    	x = i; y = j;
			    }
			    vis[i][j] = false;
			}
		}
		printf("%d\n",Bfs(x,y,0));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Mr__Charles/article/details/82184986