站外bfs代码错误求助
  • 板块灌水区
  • 楼主achjuncool
  • 当前回复9
  • 已保存回复9
  • 发布时间2022/6/17 20:48
  • 上次更新2023/10/27 23:08:38
查看原帖
站外bfs代码错误求助
604622
achjuncool楼主2022/6/17 20:48

题目链接qwq

这题是在bfs里的,所以我用了bfs,但是我这样求不到最优解,希望大佬们帮忙

#include <iostream>
#include <cstring>
using namespace std;
int tx, ty, sx, sy, ex, ey;
int xx[5] = {0, -1, 0, 1, 0};
int yy[5] = {0, 0, -1, 0, 1};
bool ac[21][21], vis[21][21];
char te;
struct node{
	int x, y, step;
};
void bfs(int p, int q){
	memset(vis, false, sizeof(vis));
	int head = 1, tail = 2, nx, ny, minn = 500000;
	node qu[450];
	qu[1].x = p;
	qu[1].y = q;
	qu[1].step = 1;
	vis[p][q] = true;
	while(head <= tail){
		head++;
		node t;
		t.x = qu[head - 1].x;
		t.y = qu[head - 1].y;
		t.step = qu[head - 1].step;
		if(t.x == ex && t.y == ey){
			if(t.step < minn){
				minn = t.step;
			}
		}
		for(int i = 1; i <= 4; i++){
			nx = t.x + xx[i];
			ny = t.y + yy[i];
			if(nx >= 1 && nx <= tx && ny >= 1 && ny <= ty && ac[nx][ny] && !vis[nx][ny]){
				tail++;
				vis[nx][ny] = true;
				qu[tail].x = nx;
				qu[tail].y = ny;
				qu[tail].step = t.step + 1;
			}
		}
	}
	for(int i = 1; i <= tail; i++){
		cout << qu[i].x << " " << qu[i].y << " " << qu[i].step << endl;
	}
	if(minn != 500000) cout << minn << endl;
	else cout << "-1" << endl;
}
int main(){
	while(true){
		cin >> tx >> ty;
		if(tx == 0 && ty == 0){
			break;
		}
		memset(ac, false, sizeof(ac));
		for(int i = 1; i <= tx; i++){
			for(int j = 1; j <= ty; j++){
				cin >> te;
				if(te == '.'){
					ac[i][j] = true;
				} else if(te == '@'){
					sx = i;
					sy = j;
					ac[i][j] = true;
				} else if(te == '*'){
					ex = i;
					ey = j;
					ac[i][j] = true;
				}
			}
		}
		bfs(sx, sy);
	}
    return 0;
}
2022/6/17 20:48
加载中...