构建邻接矩阵有向图并进行最短路径算法和深度分析
这是我已经写的一部分代码
还有报错:
0x00007FF75D966847 处(位于 第一次实习.exe 中)引发的异常: 0xC0000005: 写入位置 0x000000CEF2400000 时发生访问冲突。
该怎么修改,并完善代码
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
//结构体
struct City { //图的顶点
string country, city;
float latitude, longitude;//经纬度
};
struct Route {
string start_city, end_city, transport, other_info;//起点,终点,交通工具,其他信息
float time, cost;//时间,花费
};
struct Graph {
Route arcs[199][199];//二维数组
City vexs[199];//顶点数据信息
int vexnum, arcnum;//顶点数和弧数
};
int LocateVex(string &G,City* c) {
int i = 0;
for (; i < 199; i++)
{
if (G == c[i].city) {
break;
}
else {
return -1;
}
}
return i;
}
int main()
{
//读取 cities 表
FILE* fp;
fp = fopen("C:\\Users\\张宇航\\Desktop\\集中实习\\cities.csv", "r");
if (!fp) {
printf("ERROR!!!");
exit(0);
}
City city[199];
char ch;
float f;
int i = 0, j = 0;
while (!feof(fp))
{
//存储国家名
ch = fgetc(fp);
for (; ch != ','; ch = fgetc(fp))
{
city[i].country += ch;
}
//存储城市名
ch = fgetc(fp);
for (; ch != ','; ch = fgetc(fp))
{
city[i].city += ch;
}
//存储经纬度
fscanf(fp, "%f,", &f);
city[i].latitude = f;
fscanf(fp, "%f\n", &f);
city[i].longitude = f;
i++;
}
fclose(fp);
//读取 routes 表
FILE* fp1;
fp1 = fopen("C:\\Users\\张宇航\\Desktop\\集中实习\\routes.csv", "rt");
if (!fp1) {
printf("ERROR!!!");
exit(0);
}
Route route[1975];
i = 0;
while (!feof(fp1))
{
//存储起点城市
ch = fgetc(fp1);
for (; ch != ','; ch = fgetc(fp1))
{
route[i].start_city += ch;
}
//存储终点城市
ch = fgetc(fp1);
for (; ch != ','; ch = fgetc(fp1))
{
route[i].end_city += ch;
}
//存储交通工具
ch = fgetc(fp1);
for (; ch != ','; ch = fgetc(fp1))
{
route[i].transport += ch;
}
//存储时间和花费
fscanf(fp1, "%f,", &route[i].time);
fscanf(fp1, "%f,", &route[i].cost);
//存储其他信息
ch = fgetc(fp1);
for (; ch != '\n'; ch = fgetc(fp1))
{
route[i].other_info += ch;
}
i++;
}
//建立邻接矩阵
Graph graph;
graph.arcnum = 1975;
graph.vexnum = 199;
//构建图
//依次录入顶点的数据
for (int i = 0; i < (graph.vexnum); i++)
{
graph.vexs[i] = city[i];
}
//初始化二维矩阵
for (int i = 0; i < graph.vexnum; i++)
{
for (int j = 0; j < graph.vexnum; j++)
{
if (i == j) {
graph.arcs[i][j].cost = 0;
graph.arcs[i][j].time = 0;
}
else {
graph.arcs[i][j].cost = 1;
graph.arcs[i][j].time = 1;
}
}
}
//添加弧数据
for (int i = 0; i < graph.arcnum; i++)
{
int sta = LocateVex(route[i].start_city, city);
int end = LocateVex(route[i].end_city, city);
graph.arcs[sta][end].cost = route[i].cost;
graph.arcs[sta][end].time = route[i].time;
}
return 0;
}