繁体   English   中英

使用BFS的最短距离

[英]Shortest distance using BFS

我正在尝试解决这个SPOJ问题 该问题要求找到每个black(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");
    }
}

异丁酮

尝试这个:

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 [] []执行此操作。

您将结果翻倍的原因可能是因为您在配对的顶点之间运行了BFS两次。

但是我不确定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM