任何人都可以帮助我吗?它给了我一个错误的号码。矩阵[i] [j] .spath填充了正确的值,但是当我返回任何两个节点之间的最短路径时,它会给我一个错误的数字。编译器给我这个函数返回错误的数字?
警告:控制到达非void函数
末但是if语句,其中i检查是否达到最终总是会执行这样return语句,因为我在main()中设置结束坐标。但我注意到当我添加返回1或返回任何在函数结束时,它会给出正确的结果。这是一种规则还是什么?我已经写了一个这样的函数,我有一个if语句和唯一的return语句,并且它没有问题。谢谢:)
#include <iostream>
#include <queue>
using namespace std;
struct node
{
int x,y,spath,val;
}v,c;
node mat[100][100];
int dy[] = {-1,1,0,0}, dx[] = {0,0,-1,1}, n, m;
void input()
{
cin >> n >> m;
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
cin >> mat[i][j].val;
mat[i][j].spath = 0;
}
}
}
int shortest_path(node start, node end)
{
queue<node> q;
q.push(start);
mat[start.y][start.x].val = 1;
while (!q.empty())
{
v = q.front();
q.pop();
for (int i=0; i<4; i++) {
c.y = v.y + dy[i];
c.x = v.x + dx[i];
if (c.y == end.y && c.x == end.x) {
return mat[v.y][v.x].spath + 1;
}
else if (c.y >=0 && c.y < n && c.x >=0 && c.x < m && mat[c.y][c.x].val == 0)
{
mat[c.y][c.x].val = 1;
mat[c.y][c.x].spath = mat[v.y][v.x].spath + 1;
q.push(c);
}
}
}
}
int main()
{
node start,end;
start.x = start.y = 0;
end.y = end.x = 4;
input();
cout << shortest_path(start,end) << endl;
return 0;
}
你期望输出是什么?你觉得'shortest_path'会返回什么结果? –
你应该在shortest_path(node start,node end)结束时返回一些有意义的东西:如果没有从开始到结束的路径,会发生什么(例如,cin为mat [] []。val提供了一个非零次对角线)?然后你用一个未定义的值从shortest_path中删除。 – Tobias
你使用什么编译器/平台?似乎使用g ++/linux正常工作。 – LeGEC