求助bfs!!
  • 板块灌水区
  • 楼主samzhangjy
  • 当前回复1
  • 已保存回复1
  • 发布时间2021/4/25 20:55
  • 上次更新2023/11/5 00:07:41
查看原帖
求助bfs!!
235561
samzhangjy楼主2021/4/25 20:55

谢谢各位大佬了,思路就是先打一遍标记看哈利哪里能看见奖杯,然后bfs到看到奖杯的地方并返回步数。题目:P2199

只有70分,#4 #5 #10WA。

代码:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 5005;

char a[MAXN][MAXN];
int vis[MAXN][MAXN];
bool see[MAXN][MAXN];
int n, m;
int dx[8] = {-1, 1, 0, 0, -1, -1, 1, 1}, dy[8] = {0, 0, -1, 1, -1, 1, -1, 1};
struct point {
	int x, y;
};
queue <point> q;
int x1, y1, x2, y2;

void pre(point p) {
	see[p.x][p.y] = 1;
	// cout << p.x << ' ' << p.y << endl;
	for (int i = 0; i < 8; i++) {
		int x = p.x + dx[i], y = p.y + dy[i];
		while(x > 0 && x <= n && y > 0 && y <= m && a[x][y] != 'X') {
			see[x][y] = 1;
			x += dx[i], y += dy[i];
		}
	}
	see[p.x][p.y] = 1;
}

int bfs(point start, point end) {
	q.push(start);
	while (!q.empty()) {
		point tmp = q.front();
		if (see[tmp.x][tmp.y]) return vis[tmp.x][tmp.y];
		for (int i = 0; i < 4; i++) {
			point np = tmp;
			np.x += dx[i], np.y += dy[i];
			if (np.x > 0 && np.x <= n && np.y > 0 && np.y <= m && a[np.x][np.y] != 'X' && !vis[np.x][np.y]) {
				vis[np.x][np.y] = vis[tmp.x][tmp.y] + 1;
				q.push(np);
			}
		}
		q.pop();
	}
	return -1;
}

int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) cin >> a[i][j];
	}
	cin >> x1 >> y1 >> x2 >> y2;
	while (x1 && y1 && x2 && y2) {
		point start, end;
		start.x = x2, start.y = y2;
		end.x = x1, end.y = y1;
		memset(see, 0, sizeof(see));
		memset(vis, 0, sizeof(vis));
		while (!q.empty()) q.pop();
		pre(end);
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= m; j++) cout << see[i][j];
			cout << endl;
		}
		int ans = bfs(start, end);
		if (ans > 0) cout << ans << endl;
		else cout << "Poor Harry" << endl;
		cin >> x1 >> y1 >> x2 >> y2;
	}
	return 0;
}

谢谢各位神犇!!!qwq

2021/4/25 20:55
加载中...