forked from deutranium/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBreadthFirstSearch.cs
64 lines (59 loc) · 1.43 KB
/
BreadthFirstSearch.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Graph{
private int _V;
LinkedList<int>[] _adj;
public Graph(int V)
{
_adj = new LinkedList<int>[V];
for(int i = 0; i < _adj.Length; i++)
{
_adj[i] = new LinkedList<int>();
}
_V = V;
}
public void AddEdge(int v, int w)
{
_adj[v].AddLast(w);
}
public void BFS(int s)
{
bool[] visited = new bool[_V];
for(int i = 0; i < _V; i++)
visited[i] = false;
LinkedList<int> queue = new LinkedList<int>();
visited[s] = true;
queue.AddLast(s);
while(queue.Any())
{
s = queue.First();
Console.Write(s + " " );
queue.RemoveFirst();
LinkedList<int> list = _adj[s];
foreach (var val in list)
{
if (!visited[val])
{
visited[val] = true;
queue.AddLast(val);
}
}
}
}
static void Main(string[] args)
{
Graph g = new Graph(4);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(1, 2);
g.AddEdge(2, 0);
g.AddEdge(2, 3);
g.AddEdge(3, 3);
Console.Write("Following is Breadth First " +
"Traversal(starting from " +
"vertex 2)\n");
g.BFS(2);
}
}