ABC387 D BFS wa*16求调
  • 板块学术版
  • 楼主Nulluer
  • 当前回复3
  • 已保存回复3
  • 发布时间2025/1/4 21:45
  • 上次更新2025/1/4 22:23:47
查看原帖
ABC387 D BFS wa*16求调
1333803
Nulluer楼主2025/1/4 21:45
#include <bits/stdc++.h>
using namespace std;
struct xy {
	int x, y, p;
};
int h, w, sx, sy, t0, t1;
int py0[2][2] = {{0, -1}, {0, 1}}, py1[2][2] = {{-1, 0}, {1, 0}};
char mp[1005][1005];
int vis[1005][1005];
queue<xy> q;
int move0 (int tx, int ty, int t) {
	for (int i = 0; i < 2; ++i) {
		int ttx = tx + py0[i][0];
		int tty = ty + py0[i][1];
		if (ttx > h || ttx <= 0 || tty > w || tty <= 0 || mp[ttx][tty] == '#') {
			continue;
		}
		if ((vis[ttx][tty] <= t) && vis[ttx][tty]) {
			continue;
		}
		q.push((xy) {
			ttx, tty, 0
		});
		vis[ttx][tty] = t;
		if (mp[ttx][tty] == 'G') {
			return t - 1;
		}
	}
	return -1;
}
int move1 (int tx, int ty, int t) {
	for (int i = 0; i < 2; ++i) {
		int ttx = tx + py1[i][0];
		int tty = ty + py1[i][1];
		if (ttx > h || ttx <= 0 || tty > w || tty <= 0 || mp[ttx][tty] == '#') {
			continue;
		}
		if ((vis[ttx][tty] <= t) && vis[ttx][tty]) {
			continue;
		}
		q.push((xy) {
			ttx, tty, 1
		});
		vis[ttx][tty] = t;
		if (mp[ttx][tty] == 'G') {
			return t - 1;
		}
	}
	return -1;
}
int bfs () {
	q.push((xy) {
		sx, sy, -1
	});
	vis[sx][sy] = 1;
	while (!q.empty()) {
		int tx = q.front().x;
		int ty = q.front().y;
		int tp = q.front().p;
		int t = vis[tx][ty] + 1;
		q.pop();
		if (tp == -1) {
			t0 = move0(tx, ty, t);
			if (t0 != -1) {
				return t0;
			}
			t1 = move1(tx, ty, t);
			if (t1 != -1) {
				return t1;
			}
		} else if (tp == 0) {
			t1 = move1(tx, ty, t);
			if (t1 != -1) {
				return t1;
			}
		} else if (tp == 1) {
			t0 = move0(tx, ty, t);
			if (t0 != -1) {
				return t0;
			}
		}
	}
	return -1;
}
int main() {
	cin >> h >> w;
	for (int i = 1; i <= h; ++i) {
		for (int j = 1; j <= w; ++j) {
			cin >> mp[i][j];
			if (mp[i][j] == 'S') {
				sx = i;
				sy = j;
			}
		}
	}
	cout << bfs() << "\n";
	for (int i = 1; i <= h; ++i) {
		for (int j = 1; j <= w; ++j) {
			cout << vis[i][j] << " ";
		}
		cout << "\n";
	}
	return 0;
}
2025/1/4 21:45
加载中...