Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d865d97

Browse files
geeks graph
1 parent 0a30879 commit d865d97

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package geeksForGeeks.binarySearchTree;
2+
3+
4+
// Java program to print BFS traversal from a given source vertex.
5+
// BFS(int s) traverses vertices reachable from s.
6+
import java.io.*;
7+
import java.util.*;
8+
9+
// This class represents a directed graph using adjacency list
10+
// representation
11+
public class Graph
12+
{
13+
private int V; // No. of vertices
14+
private LinkedList<Integer> adj[]; //Adjacency Lists
15+
16+
// Constructor
17+
Graph(int v)
18+
{
19+
V = v;
20+
adj = new LinkedList[v];
21+
for (int i=0; i<v; ++i)
22+
adj[i] = new LinkedList();
23+
}
24+
25+
// Function to add an edge into the graph
26+
void addEdge(int v,int w)
27+
{
28+
adj[v].add(w);
29+
}
30+
31+
// prints BFS traversal from a given source s
32+
void BFS(int s)
33+
{
34+
// Mark all the vertices as not visited(By default
35+
// set as false)
36+
boolean visited[] = new boolean[V];
37+
38+
// Create a queue for BFS
39+
LinkedList<Integer> queue = new LinkedList<Integer>();
40+
41+
// Mark the current node as visited and enqueue it
42+
visited[s]=true;
43+
queue.add(s);
44+
45+
while (queue.size() != 0)
46+
{
47+
// Dequeue a vertex from queue and print it
48+
s = queue.poll();
49+
System.out.print(s+" ");
50+
51+
// Get all adjacent vertices of the dequeued vertex s
52+
// If a adjacent has not been visited, then mark it
53+
// visited and enqueue it
54+
Iterator<Integer> i = adj[s].listIterator();
55+
while (i.hasNext())
56+
{
57+
int n = i.next();
58+
if (!visited[n])
59+
{
60+
visited[n] = true;
61+
queue.add(n);
62+
}
63+
}
64+
}
65+
}
66+
67+
// Driver method to
68+
public static void main(String args[])
69+
{
70+
Graph g = new Graph(4);
71+
72+
g.addEdge(0, 1);
73+
g.addEdge(0, 2);
74+
g.addEdge(1, 2);
75+
g.addEdge(2, 0);
76+
g.addEdge(2, 3);
77+
g.addEdge(3, 3);
78+
79+
System.out.println("Following is Breadth First Traversal "+
80+
"(starting from vertex 2)");
81+
82+
g.BFS(2);
83+
}
84+
}
85+
// This code is contributed by Aakash Hasija

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /