求助,只有十分
查看原帖
求助,只有十分
317198
MilkyCoffee楼主2021/1/9 14:59

如题,小测的时候没调出来的题求助。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int NR = 1e2 + 5;

struct node {
	int from, x, y, res;
};

int n, sx, sy, ex, ey, ans = 2e9;
char s[NR][NR];
bool vis[NR][NR];

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

queue <node> q;
void bfs() {
	memset(vis, 0, sizeof(vis));
	q.push((node){5, sx, sy, 0});
	vis[sx][sy] = 1;
	while (!q.empty()) {
		int from = q.front().from, x = q.front().x, y = q.front().y, res = q.front().res;
		q.pop();
		if (x == ex && y == ey) {
			ans = min(ans, res - 1);
		}
		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i], ny = y + dy[i];
			if (nx >= 1 && nx <= n && ny >= 1 && ny <= n && !vis[nx][ny] && s[nx][ny] != 'x') {
				int tmp = 0;
				tmp = res;
				if (from != i) tmp++;
				q.push((node){i, nx, ny, tmp});
				vis[nx][ny] = 1;
			}
		}
	}
}

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			cin >> s[i][j];
			if (s[i][j] == 'A') {
				sx = i;
				sy = j;
			} if (s[i][j] == 'B') {
				ex = i;
				ey = j;
			}
		}
	}
	
	bfs();
	cout << ans << endl;
	return 0;
}
2021/1/9 14:59
加载中...