c++ - 控制到达非 void 函数的末尾

标签 c++ breadth-first-search

这段代码应该可以完美运行并给出正确的结果,但事实并非如此。我用了调试器,一切正常。 c.ic.j 在函数返回之前具有正确的值。我确保在开始和结束之间总是有一条路径,所以这不是问题。 pathvis 数组也填充了正确的值。所以唯一的问题是它何时返回。它给出随机的大数字。只有当我在函数末尾放置一个 return 语句时它才有效。但是我可以创建一个函数,只在 if 子句中放置一个 return 语句并且它可以工作。是否存在某种规则,函数末尾必须有任何类型的 return 语句?为了测试它,我输入了 3x3 二维数组和 1。有什么解决办法吗?

编辑:我在 ideone 上运行它,它在函数末尾没有 return 语句的情况下工作。我的一个 friend 也在他的电脑上测试过它也有效。我在 Windows 7 上使用代码块。可能是什么问题?

link to ideone

#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <cmath>

using namespace std;

struct crd {
    int i,j;
};

bool vis[50][50];
int map[50][50];
int path[50][50];

int di[4] = {1,-1,0,0};
int dj[4] = {0,0,1,-1};

int bfs(crd start, crd end, int n, int m)
{
    queue<crd> q;
    crd t,c;
    q.push(start);
    vis[start.i][start.j] = 1;
    path[start.i][start.j] = 0;

    while (!q.empty()) {
        t = q.front();
        q.pop();

        for (int i=0; i<4; i++) {
            c.i = t.i + di[i]; 
            c.j = t.j + dj[i]; 
            if (c.i >= 0 && c.j >= 0 && c.i < n && c.j < m) {
                if (map[c.i][c.j] != -1 && vis[c.i][c.j] != 1) {
                    q.push(c);
                    vis[c.i][c.j] = 1; 
                    path[c.i][c.j] = path[t.i][t.j] + 1; 
                    if (c.i == end.i && c.j == end.j)
                        return path[end.i][end.j];
                }
            }
        }

    }
    // if i put this: return path[end.i][end.j]; it works
}

int main()
{
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++)
            cin >> map[i][j];
    }

    crd s,e;
    s.i = s.j = 0;
    e.i = e.j = 2;

    int sp = bfs(s,e,3,3);

    cout << sp << endl;


    return 0;

}

最佳答案

编译器非常基础 - 它无法知道您的函数将始终在您的 if 中返回,在 if 中,在另一个 if< 中while 循环内的 for 循环内。所以它警告你你可能不会从函数返回任何东西。最简单的解决方法是在最后返回适当的值,并且只在您现在返回的那一点跳出循环。

关于c++ - 控制到达非 void 函数的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957919/

相关文章:

c# - 将复杂结构从 C++ 编码到 C#

c++ - 如何知道方法中的对象地址?

c++ - 关于函数调用中的异常安全

c++ - 是否可以在 Visual Studio 中使用 Bazel 构建代码?

c++ - 程序的意外输出

c++ - 指针所有权

java - 这个网络爬虫是做广度优先搜索还是深度优先搜索?

breadth-first-search - 广度优先遍历有向图与无向图

c++ - 生成直到给定数字 N 的步进数字

algorithm - 在矩阵中的源和目标之间建立路径所需的最少翻转