梅开二度
查看原帖
梅开二度
1073754
__szh_DNCB__楼主2024/10/1 16:43

bfs 死循环

#include<bits/stdc++.h>
using namespace std;
int n;
pair<int,int> beginning,ending;
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
bool s[1005][1005];
bool isgo[1005][1005];

bool check(int x,int y){
	if (x <= 0 || x >= n || y <= 0 || y >= n || !(s[x][y]) || isgo[x][y]){
		return false;
	}return true;
}

int bfs(){
	int cnt = 0;
	queue<pair<int,int>> q;
	q.push(make_pair(beginning.first,beginning.second));
	while (q.size() != 0){
		pair<int,int> f = q.front();
		q.pop();
		if (f == ending)return cnt;
		isgo[f.first][f.second] = true;
		for (int i=0;i<4;i++){
			if (check(f.first + dx[i],f.second + dy[i])){
				q.push({f.first+dx[i],f.second + dy[i]});
			}
		}
		cnt++;
	}
}

int main(){
	cin >> n;
	for (int i=1;i<=n;i++){
		for (int j=1;j<=n;j++){
			int v;cin >> v;
			if (v == 1)s[i][j] = false;
			else s[i][j] = true;
		}
	}
	cin >> beginning.first >> beginning.second;
	cin >> ending.first >> ending.second;
	cout << bfs();
	return 0;
}
2024/10/1 16:43
加载中...