加权图的开始和结束的最短路径
Shortest path given beginning and end of a weighted graph
我必须在文件中读取才能创建加权图。必须使用文件输入找到最短路径。文件将作为第一行=数字和下方的每一行构造,其中3个数字给出:0 1 2,其中0是边缘的开始,1是边的末端,而2是重量。我尝试在创建图形时尝试实现邻接矩阵,但没有运气。任何建议都将不胜感激。
尝试重组我在文件中阅读的方式,并尝试调整FindshortEstpath功能。
void createGraph(string file_name) //Function to create a graph based on a file, whose name is file_name.
{
ifstream f(file_name);
if (f.fail())
{
return;
}
string line;
getline(f, line);
int num = stoi(line);
numVertices = num;
int data[50][50];
string line2;
int num1 = 0, num2 = 0, num3 = 0;
while (!f.eof())
{
f >> num1;
f >> num2;
f >> line2;
num3 = stoi(line2);
data[num1][num2] = num3;
}
}
//////////////////shortest path function
string findShortestPath(int start, int end)
{
int data[numVertices][numVertices];
int dist[numVertices];
bool sptSet[numVertices];
int parent[numVertices];
for (int i = 0; i < numVertices; i++)
{
parent[0] = -1;
dist[i] = INT_MAX;
sptSet[i] = false;
}
dist[start] = 0;
for (int count = 0; count < numVertices - 1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = true;
if (sptSet[u] == end)
break;
for (int v = 0; v < numVertices; v++)
if (!sptSet[v] && data[u][v] && dist[u] + data[u][v] < dist[v])
{
parent[numVertices] = end;
dist[v] = dist[u] + data[u][v];
}
}
printSolution(parent);
输出不是输出最短路径,并且正在打印随机数。
在您的findShortestPath
功能data[numVertices][numVertices]
中与createGraph
函数中的data
变量不同。
查看此https://www.geeksforgeeks.orgs.org/scope-of-variables-in-in-c/或尝试在变量范围上查找其他来源。
在您的函数findShortestPath
中,您已声明了一个名为data
的本地数组,该数组应该存储邻接矩阵数据。但是,您从未写过任何数据!考虑将矩阵作为函数参数传递。您的功能签名应该看起来像这样:
findShortestPath(int** data, int numVertices, int start, int end)
另外,避免使用VLA,因为它不是标准的一部分。考虑使用new
在堆上创建二维数组。(并且完成完成后不要忘记做delete[]
!(
,也可以使用std::vector<std::vector<int>>
,如果您不想手动管理数组的寿命。
相关文章:
- 内存效率表示最短路径的方法?
- 用于查找网格中最短路径的算法
- 查找最短路径算法
- BFS 打印最短路径
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 使用C++具有两个数字的最短路径算法.(C++)
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 如何使用贝尔曼-福特算法返回所有具有捆绑重量的最短路径?
- 使用优先级队列查找所有与 Dijkstra 相同的最短路径
- 尝试在图形中查找最短路径时的无限循环
- C++计算有向图中的最短路径
- 使用BFS存储和打印最短路径
- 如何制作由原始图形的最短路径边组成的新图形
- 有没有一种方法可以使用弗洛伊德-沃歇尔算法给出最短路径,其中存在负权重循环而不允许重叠边缘?
- 加权图的开始和结束的最短路径
- 使 c++11 Dijkstra 实现返回最短路径
- 弗洛伊德最短路径算法C++
- Dijkstra 最短路径算法性能 std::p riority_queue VS std::set.
- 在 stl 中使用向量和对的最有效实现 Dijkstra 最短路径C++