-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cs
More file actions
73 lines (58 loc) · 1.48 KB
/
BFS.cs
File metadata and controls
73 lines (58 loc) · 1.48 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
using System;
using System.Collections;
using System.Collections.Generic;
namespace algos
{
class Graph
{
private int _v;
List<int>[] adj = null;
Graph(int v)
{
_v = v;
adj = new List<int>[v];
for (int i = 0; i < v; i++)
{
adj[i] = new List<int>();
}
}
public void AddEdge(int v, int w)
{
adj[v].Add(w);
}
public void BFS(int s)
{
bool[] visited = new bool[_v];
visited[s] = true;
Queue<int> q = new Queue<int>();
q.Enqueue(s);
while (q.Count != 0)
{
s = q.Peek();
Console.Write(s + " ");
q.Dequeue();
foreach (var i in adj[s])
{
if (!visited[i])
{
visited[i] = true;
q.Enqueue(i);
}
}
}
}
public static void MainC(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.WriteLine("Following is Depth First Traversal " +
"(starting from vertex 2)");
g.BFS(2);
}
}
}