Skip to content

Commit 0e4a76a

Browse files
committed
DFS in Graph
1 parent 86fa1fc commit 0e4a76a

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Algorithm/GraphDFS.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include<iostream>
2+
#include<stack>
3+
using namespace std;
4+
5+
const static int INF = __INT_MAX__;
6+
7+
/*
8+
A B
9+
/ \ /
10+
/ \ /
11+
/ C------D
12+
E /
13+
\ /
14+
\ /
15+
F
16+
*/
17+
18+
int matrix[6][6] = {{INF, INF, 1, INF, 1, INF},
19+
{INF, INF, 1, INF, INF, INF},
20+
{1, 1, INF, 1, INF, INF},
21+
{INF, INF, 1, INF, INF, 1},
22+
{1, INF, INF, INF, INF, 1},
23+
{INF, INF, INF, 1, 1, INF}
24+
};
25+
26+
int visited[6] = {0};
27+
28+
void DFS(stack<char>& s, char ch)
29+
{
30+
if (s.empty())
31+
return;
32+
cout << ch;
33+
for (int i = 0; i < 6; i++)
34+
{
35+
if (matrix[ch - 'A'][i] == 1 && visited[i] == 0)
36+
{
37+
visited[i] = 1;
38+
s.push('A' + i);
39+
DFS(s, s.top());
40+
}
41+
}
42+
s.pop();
43+
}
44+
45+
int main(int argc, char const *argv[])
46+
{
47+
stack<char> s;
48+
char begin = 'A';
49+
cout << "DFS begin from A:\n";
50+
s.push(begin);
51+
visited[0] = 1;
52+
DFS(s, s.top());
53+
cout << endl;
54+
return 0;
55+
}

0 commit comments

Comments
 (0)