-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFS.cpp
122 lines (87 loc) · 2 KB
/
DFS.cpp
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// bagli liste yapisi ile graph larda DFS dolanma kodu
// Ahmet Furkan DEMIR
#include <stdio.h>
#include <stdlib.h>
#include <list>
using namespace std;
// node sayisi
#define count 6
// komsulari tutan yapi
typedef struct queue{
int val;
struct queue *next;
}queue;
// nodelerin hepsini tutan yapi
typedef struct Node{
struct queue *list[count];
}node;
// ana yapiya erisilen yer
node * root;
// root init
void __init__(){
root=(node *)malloc(sizeof(node));
}
// dugumleri birbirine bagladigimiz yer
// v den w ye baglanti gerceklesir
void addEdge(int v, int w){
// ilk komsu eklenir
if(root->list[v]==NULL){
root->list[v]=(queue *)malloc(sizeof(queue));
root->list[v]->val=w;
root->list[v]->next=NULL;
}
// diger komsular eklenir
else{
queue *temp=root->list[v];
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=(queue *)malloc(sizeof(queue));
temp->next->val=w;
temp->next->next=NULL;
}
}
void DFS_recursiv(int v, bool visited[]){
// dugum yazdirilir ve gidildi olarak isaretlenir
visited[v] = true;
printf("%d ", v);
// dugumun tum komsulari
// en sona kadar ilerler ekrana yazdirir ve komsular bitince diger taraftan devam eder.
queue *temp= root->list[v];
while(temp!=NULL){
if (!visited[temp->val])
// bu komsuya daha once girilmediyse iceri girilir ve kod recursiv olarak devam eder
DFS_recursiv(temp->val, visited);
// sonraki komsuya gecilir.
temp=temp->next;
}
}
// DFS dolasma
void DFS(int s){
// tum komsular gidildimi diye boolean liste
bool* visited = new bool[count];
for (int i = 0; i < count; i++)
visited[i] = false;
// recursiv fonksiyon
// graphı DFS olarak dolasacak
DFS_recursiv(s, visited);
}
// main
int main()
{
// init ve ekleme islemi
__init__();
addEdge(0, 1);
addEdge(0, 3);
addEdge(1, 2);
addEdge(3, 5);
addEdge(5, 0);
addEdge(5, 3);
addEdge(5, 4);
addEdge(2, 3);
addEdge(2, 4);
addEdge(4, 2);
// DFS dolasma, root olarak 0 secildi.
DFS(0);
return 0;
}