Calculate the pit of the Lanqiao Cup

Participated in the Blue Bridge Cup simulation competition of Jie Suanke. When doing a labyrinth problem, I first used dfs to do it, and it timed out. Later, I remembered that this kind of problem should be done with bfs, and then found a hole when doing it. . . .

topic:

enter:

3 4
..*.
..*.
..*.
2
2 2 2 4
3 1 1 4
3 4

Output:

3

Problem-solving idea: This problem can be used directly to find the shortest path with bfs. What needs to be paid attention to is the pit of the portal. Under normal circumstances, what we consider is that one point is transmitted to another point. However, the data type given by the question may be transmitted from one point to another, and then the point to be transmitted to has its own portal, and it will be transmitted again.

AC code:

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 1005;

int n, m, q, x, y, ans;
char G[maxn][maxn];
bool vis[maxn][maxn];
struct N{
	int x, y, step;
	N(int a, int b, int s):x(a), y(b), step(s){}
};
queue<N> Q;

struct D{
	int tx,ty;
}Tp[maxn][maxn];

int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

bool ok(int u, int v){
	if(u <= 0 || v <= 0 || u > n || v > m || G[u][v] == '*')return false;
	return true;
}

void bfs(int u, int v, int w){
	N tem = N(0, 0, 0);
	Q.push(N(u, v, w));
	vis[u][v] = true;
	while(!Q.empty()){
		tem = Q.front();
		Q.pop();
		if(tem.x == x && tem.y == y){
			ans = min(ans, tem.step);
		}
		while(Tp[tem.x][tem.y].tx != 0 && Tp[tem.x][tem.y].ty != 0 && G[Tp[tem.x][tem.y].tx][Tp[tem.x][tem.y].ty] != '*'){	
		//坑点,因为传送到某一点后,哪一点可能还有传送门,因此,必须循环 
			int x1 = tem.x, y1 = tem.y;
			tem.x = Tp[x1][y1].tx;
			tem.y = Tp[x1][y1].ty;
		}
		if(tem.x == x && tem.y == y){
			ans = min(ans, tem.step);
		}
		for(int i = 0; i < 4;i++){
			int nx = tem.x + dx[i];
			int ny = tem.y + dy[i];
			int nw = tem.step + 1;
			if(ok(nx, ny) && !vis[nx][ny]){
				vis[nx][ny] = true;
				Q.push(N(nx, ny, nw));
			}
		}
	}	
}

int main(){
	int a, b, c, d;
	while(scanf("%d%d", &n, &m) != EOF){
		memset(Tp, 0, sizeof Tp);
		memset(G, 0, sizeof G);
		memset(vis, false, sizeof vis);
		ans = 0x3f3f3f3f;
		while(!Q.empty())Q.pop();
		for(int i = 1; i <= n;i++){
			scanf("%s", G[i] + 1);//如果不加1则默认从下标0开始 
		}
		scanf("%d", &q);
		for(int i = 1; i <= q;i++){
			scanf("%d%d%d%d", &a, &b, &c, &d);
			Tp[a][b].tx = c;
			Tp[a][b].ty = d;
		}
		scanf("%d%d", &x, &y);//终点地方
		bfs(1, 1, 0);
		if(ans >= 0x3f3f3f3f / 2) 
			printf("No solution\n");
		else
			printf("%d\n", ans);
	}
	return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_40596572/article/details/104059244