#include <_dbdao.h>
#include <stdlib.h>
#include <stdio.h>
#include "List.h" //提供List的数据结构
int vertexNum;
int arcNum;
bool visited[];
const char * path="src/tinyDG.txt";
List<ArrayList<Integer>> graphListS;
List<ArrayList<Integer>> graphListF;
void GraphReverse(int v,int arcNum,List<ArrayList<Integer>> graphListS,List<ArrayList<Integer>> graphListF){
vertexNum=v;
graphListS=gS;
visited = (bool*)malloc(vertexNum * sizeof(bool));
graphListF=gF;
}
//广度优先遍历
void bfs(int v,List<ArrayList<Integer>> graphList){
Queue<Integer> que = new LinkedList<Integer>();
que.offer(v);
while (!que.isEmpty()) {
v = que.poll();
printf("%d: ", v);
visited[v] = true;
for (int i = 0; i < graphList.get(v).size(); i++) {
int k=graphList.get(v).get(i);
System.out.print(k+" ");
if (!visited[k]){
que.offer(k);
visited[k] = true;
}
}
putchar('\n');
}
}
}
int main(void)
{
FILE *in;
if((in = fopen(path, "rw")) == NULL)
{
printf("出现文件读写错误\n");
return EXIT_FAILURE;
}
List<ArrayList<Integer>> graphListS=new ArrayList<ArrayList<Integer>>();//存储有向图的邻接表
List<ArrayList<Integer>> graphListF=new ArrayList<ArrayList<Integer>>();//存储有向图的反向图的邻接表
//读取必要参数
int vertexNum;
fscanf("%d",&vertexNum);
int arcNum;
fscanf("%d", &arcNum);
for(int i=0;i<vertexNum;i++){
graphListS.add(new ArrayList<Integer>());
graphListF.add(new ArrayList<Integer>());
}
//有向图的存储
for(int i=0;i<arcNum;i++){
fscanf("%d", &u);
fscanf("%d", &v);
if(!graphListS.get(u).contains(v)){
graphListS.get(u).add(v);
}
//有向图的反向图存储
if(!graphListF.get(v).contains(u)){
graphListF.get(v).add(u);
}
}
//有向图的广度优先遍历
GraphReverse g1=new GraphReverse(vertexNum, arcNum, graphListS,null);
System.out.println("有向图的邻接表的结果是:");
g1.bfs(vertexNum/2+1,graphListS);
//有向图的反向图广度优先的遍历
GraphReverse g2=new GraphReverse(vertexNum, arcNum, null,graphListF);
System.out.println("有向图的反向图的邻接表结果是:");
g2.bfs(1,graphListF);
}
return EXIT_SUCCESS;
}
第五周作业
最新推荐文章于 2024-10-29 19:00:27 发布