Skip to content

Commit f073131

Browse files
committed
added dfs in csharp
1 parent d94c1d5 commit f073131

File tree

4 files changed

+71
-13
lines changed

4 files changed

+71
-13
lines changed

CSHARP/Program.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ public static void Main(string[] args) {
77
// BFS bfs = new BFS();
88
// bfs.manageBFS(lines);
99

10-
10+
DFS dfs = new DFS();
11+
dfs.manageDFS(lines);
1112
}
1213
}

CSHARP/dfs.cs

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
public class DFS {
5+
6+
public int nodes, edges;
7+
public bool[] vis;
8+
public List <int>[] graph;
9+
10+
public DFS() {
11+
12+
}
13+
14+
public void initDFS(int nodes, int edges) {
15+
this.nodes = nodes;
16+
this.edges = edges;
17+
18+
graph = new List<int>[nodes];
19+
for (int i = 0; i < nodes; i++) {
20+
vis = new bool[nodes];
21+
graph[i] = new List<int>();
22+
}
23+
}
24+
25+
public void dfs(int u) {
26+
Console.Write("{0} ", u);
27+
vis[u] = true;
28+
29+
for (int i = 0; i < graph[u].Count; i++) {
30+
int v = graph[u][i];
31+
if (vis[v] == false) {
32+
dfs(v);
33+
}
34+
}
35+
}
36+
37+
public void manageDFS(string[] lines) {
38+
39+
string[] line1 = lines[0].Split(' ');
40+
int nodes = int.Parse(line1[0]);
41+
int edges = int.Parse(line1[1]);
42+
43+
initDFS(nodes, edges);
44+
45+
for (int i = 1; i <= edges; i++) {
46+
string[] all_edge = lines[i].Split(' ');
47+
int u = int.Parse(all_edge[0]);
48+
int v = int.Parse(all_edge[1]);
49+
graph[u].Add(v);
50+
graph[v].Add(u);
51+
}
52+
53+
for (int i = 0; i < nodes; i++) {
54+
if (vis[i] == false) {
55+
dfs(i);
56+
}
57+
}
58+
59+
Console.WriteLine();
60+
}
61+
}

CSHARP/in.txt

+5-10
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
1-
8 10
1+
6 5
22
0 1
3-
0 2
4-
0 3
5-
0 4
6-
1 5
7-
2 5
8-
3 6
9-
4 6
10-
5 7
11-
6 7
3+
1 2
4+
2 4
5+
3 4
6+
1 5

DFS.cpp

+3-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ int main() {
4545
return 0;
4646
}
4747

48-
/******************
48+
/*
4949
INPUT
5050
---
5151
- 1st line, 6 Vertex, 5 Edge
@@ -54,8 +54,9 @@ int main() {
5454
1 2
5555
2 4
5656
3 4
57+
1 5
5758
5859
OUTPUT:
5960
-----
6061
0 1 5 2 4 3
61-
*****************/
62+
*/

0 commit comments

Comments
 (0)