gpt4 book ai didi

c++ - 使用 BFS 的最短距离

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:48:07 25 4
gpt4 key购买 nike

我正在尝试解决 this SPOJ problem .该问题要求找到每个黑色 (1) 像素的最短路径。

因为它是一个未加权的图,所以我使用了 BFS。

输入:

3 3
010
000
000

它给:

323
434
343

代替:

101
212
323

这是我的代码

#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
typedef pair < int, int >ii;
int R, C, i, j;
queue < ii > myQueue;

int visit[100][100];
int dist[100][100];
void bfs(ii s)
{
int i, j;
int count = 0;
ii node;
memset(visit, 0, sizeof(visit));
memset(dist, 0, sizeof(dist));
myQueue.push(s);
dist[node.first][node.second] = 0;

while (!myQueue.empty()) {
node = myQueue.front();
myQueue.pop();
if (visit[node.first][node.second])
continue;
visit[node.first][node.second] = 1;

//cout << node.first << " " << node.second << "\n";
i = node.first;
j = node.second;

if (j - 1 < R && j - 1 >= 0) {
myQueue.push(make_pair(i, j - 1));
if(dist[i][j - 1] == 0)
dist[i][j - 1] = dist[i][j] + 1;
}
if (j + 1 < R && j + 1 >= 0) {
myQueue.push(make_pair(i, j + 1));
if(dist[i][j+1] == 0)
dist[i][j + 1] = dist[i][j] + 1;
}
if (i - 1 < C && i - 1 >= 0) {
myQueue.push(make_pair(i - 1, j));
if(dist[i-1][j] == 0)
dist[i - 1][j] = dist[i][j] + 1;
}
if (i + 1 < C && i + 1 >= 0) {
myQueue.push(make_pair(i + 1, j));
if(dist[i+1][j] == 0)
dist[i + 1][j] = dist[i][j] + 1;
}
}
}

int main()
{
char input[100][100];
scanf("%d %d", &R, &C);
for (i = 0; i < R; i++)
scanf("%s", &input[i]);
int GRID[R][C];
for (i = 0; i < R; i++)
for (j = 0; j < C; j++)
GRID[i][j] = input[i][j] - '0';
for (i = 0; i < R; i++)
for (j = 0; j < C; j++) {
if (GRID[i][j] == 1)
bfs(make_pair(i, j));
}
for (i = 0; i < R; i++) {
for (j = 0; j < C; j++) {
printf("%d", dist[i][j]);
}
printf("\n");
}
}

ideone

最佳答案

试试这个:

if (j - 1 < R && j - 1 >= 0) {
myQueue.push(make_pair(i, j - 1));
if(dist[i][j - 1] == 0)
dist[i][j - 1] = dist[i][j] + 1;
}

对所有 dist[][] 执行此操作。

关于c++ - 使用 BFS 的最短距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11116846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com