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 c241658

Browse files
Graph BFS implemented
1 parent d865d97 commit c241658

File tree

1 file changed

+52
-19
lines changed

1 file changed

+52
-19
lines changed
Lines changed: 52 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,69 @@
11
package me.premaseem.datastructure.graph;
22

3-
import java.util.ArrayList;
3+
4+
import java.util.LinkedList;
45

56
public class Graph {
67

7-
ArrayList graphArray[];
8+
int size;
9+
LinkedList<Integer> vertex[];
810

9-
public Graph(int numOfVertices) {
10-
graphArray = new ArrayList[numOfVertices];
11-
for (int i = 0; i < graphArray.length; i++) {
12-
graphArray[i] = new ArrayList<Integer>();
11+
public Graph(int size){
12+
this.size = size;
13+
vertex = new LinkedList[size];
14+
for (int i = 0; i < size; i++) {
15+
vertex[i] = new LinkedList<>();
1316
}
14-
1517
}
1618

17-
public void addEdge(int from, int to) {
18-
graphArray[from].add(to);
19+
void addEdge(int p1, int p2 ){
20+
if(p1 > vertex.length || p2 > vertex.length){
21+
System.out.println("cannot add edge, vertex out of graph");
22+
return;
23+
}
24+
vertex[p1].add(p2);
1925
}
2026

21-
public void getAdjecents(int vertex) {
22-
ArrayList edges = graphArray[vertex];
23-
for (Object i : edges) {
24-
System.out.printf(" %s --> %s \n", vertex, i);
25-
}
27+
public static void main(String[] args) {
28+
Graph g = new Graph(5);
29+
30+
g.addEdge(0, 1);
31+
g.addEdge(0, 2);
32+
g.addEdge(1, 2);
33+
g.addEdge(2, 0);
34+
g.addEdge(2, 3);
35+
g.addEdge(3, 3);
36+
g.addEdge(0, 4);
37+
g.addEdge(4, 1);
38+
39+
g.BFS(4);
2640
}
2741

28-
public void printGraphEdges() {
29-
for (int i = 0; i < graphArray.length; i++) {
30-
for (Object obj : graphArray[i]) {
31-
System.out.printf(" %s --> %s \n", i, obj);
42+
void BFS(int v){
43+
44+
// default marked as false for visited vertex
45+
boolean[] visited = new boolean[size];
46+
47+
// form a queue to ensure get first and then connected neighbours
48+
LinkedList<Integer> q = new LinkedList<>();
49+
q.add(v);
50+
visited[v] = true;
51+
52+
while(!q.isEmpty()){
53+
Integer vert = q.poll();
54+
System.out.println(" Visiting "+vert);
55+
56+
// getting the adjacent and adding them to q if they not been visited before
57+
LinkedList<Integer> adj = this.vertex[vert];
58+
59+
for (Integer vo:adj) {
60+
if(!visited[vo]){
61+
visited[vo] = true;
62+
q.add(vo);
63+
}
3264
}
33-
}
3465

66+
}
3567
}
68+
3669
}

0 commit comments

Comments
(0)

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