-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cs
More file actions
75 lines (56 loc) · 1.32 KB
/
Copy pathbfs.cs
File metadata and controls
75 lines (56 loc) · 1.32 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
using System;
using System.Collections.Generic;
using System.Linq;
class Graph
{
int V;
LinkedList<int>[] adj;
public Graph (int ver)
{
adj = new LinkedList<int>[ver];
for (int i = 0; i < adj.Length; i++)
{
adj[i] = new LinkedList<int>();
}
V = ver;
}
public void edgeAdd(int v, int w)
{
adj[v].AddLast(w);
}
public void BFS(int start)
{
bool[] visited = new bool[V];
Array.Fill(visited, false);
LinkedList<int> q = new LinkedList<int>();
visited[start] = true;
q.AddLast(start);
while(q.Any())
{
start = q.First();
Console.WriteLine(start +" ");
q.RemoveFirst();
LinkedList<int> list = new LinkedList<int>();
list = adj[start];
foreach (var val in list)
{
if (visited[val] == false)
{
visited[val] = true;
q.AddLast(val);
}
}
}
}
static void Main(string[] arg)
{
Graph g = new Graph(5);
g.edgeAdd(0, 1);
g.edgeAdd(0, 2);
g.edgeAdd(1, 2);
g.edgeAdd(2, 0);
g.edgeAdd(2, 3);
g.edgeAdd(3, 3);
g.BFS(2);
}
}