-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph-search.cpp
More file actions
101 lines (84 loc) · 2.29 KB
/
Copy pathgraph-search.cpp
File metadata and controls
101 lines (84 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cassert>
#include <climits>
#include <queue>
#include "graph.h"
#define WHITE 0
#define GREY 1
#define BLACK 2
using namespace std;
/*
实现 bfs、dfs、topological-sort,SCC
*/
void breath_first_search(int** graph, int V, int start, int* dis, int* parent, int* color){
int i;
for(i=0; i<V; i++){
if(i != start){
color[i] = WHITE;
dis[i] = -1;
parent[i] = -1;
}
}
dis[start] = 0;
color[start] = GREY;
parent[start] = -1; // no parent
queue<int> Q;
Q.push(start);
while(! Q.empty()){
int u = Q.front(); Q.pop();
for(int i=0; i<V; i++){
if(graph[u][i] == 1 && color[i] == WHITE){
Q.push(i);
dis[i] = dis[u] + 1;
parent[i] = u;
color[i] = GREY;
}
}
color[u] = BLACK;
}
}
// 递归调用函数
void dfs_visit(int curr, int** graph, int V, int* parent, int* color, int* enter, int* finish, int* ptime){
*ptime += 1;
enter[curr] = *ptime;
color[curr] = GREY;
int i;
for(i=0; i<V; i++){
if(graph[curr][i] == 1 && color[i] == WHITE){
parent[i] = curr;
dfs_visit(i, graph, V, parent, color, enter, finish, ptime);
}
}
*ptime += 1;
finish[curr] = *ptime;
color[curr] = BLACK;
}
void deep_first_search(int** graph, int V, int* parent, int* color, int* enter, int* finish){
int i;
for(i=0; i<V; i++){
parent[i] = -1;
color[i] = WHITE;
}
int time = 0;
for(i=0; i<V; i++){
if(color[i] == WHITE)
dfs_visit(i, graph, V, parent, color, enter, finish, &time);
}
}
int main(int argc, char const *argv[]) {
int V;
int** graph;
graph = read_unweighted_graph("graph.txt", V, false);
//print_graph(graph, V);
int* dis = (int*)malloc(V * sizeof(int));
int* parent = (int*)malloc(V * sizeof(int));
int* color = (int*)malloc(V * sizeof(int));
int* enter = (int*)malloc(V * sizeof(int));
int* finish = (int*)malloc(V * sizeof(int));
//breath_first_search(graph, V, 1, dis, parent, color);
deep_first_search(graph, V, parent, color, enter, finish);
print_path(parent, 1, 3);
return 0;
}