-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
106 lines (91 loc) · 3.17 KB
/
Graph.java
File metadata and controls
106 lines (91 loc) · 3.17 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import java.util.*;
public class Graph {
private int vertices;
private int[][] adjacencyMatrix;
public Graph(int vertices) {
this.vertices = vertices;
adjacencyMatrix = new int[vertices][vertices];
}
public void addEdge(int source, int destination) {
adjacencyMatrix[source][destination] = 1;
}
public void bfs(int startVertex) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.add(startVertex);
boolean isFirst = true;
while (!queue.isEmpty()) {
int currentVertex = queue.poll();
if (isFirst) {
System.out.print(currentVertex);
isFirst = false;
} else {
System.out.print("->" + currentVertex);
}
for (int neighbor = 0; neighbor < vertices; neighbor++) {
if (adjacencyMatrix[currentVertex][neighbor] == 1 && !visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);
}
}
}
System.out.println();
}
public void dfs(int startVertex) {
boolean[] visited = new boolean[vertices];
Stack<Integer> stack = new Stack<>();
visited[startVertex] = true;
stack.push(startVertex);
boolean isFirst = true;
while (!stack.isEmpty()) {
int currentVertex = stack.pop();
if (isFirst) {
System.out.print(currentVertex);
isFirst = false;
} else {
System.out.print("->" + currentVertex);
}
for (int neighbor = 0; neighbor < vertices; neighbor++) {
if (adjacencyMatrix[currentVertex][neighbor] == 1 && !visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
}
}
}
System.out.println();
}
public void printGraph() {
for (int i = 0; i < vertices; i++) {
System.out.print("Vertex " + i + " is connected to: ");
for (int j = 0; j < vertices; j++) {
if (adjacencyMatrix[i][j] == 1) {
System.out.print(j + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of vertices: ");
int vertices = sc.nextInt();
System.out.println();
Graph graph = new Graph(vertices);
System.out.println("Enter the source and destination vertex, or -1 to exit: ");
while (true) {
int source = sc.nextInt();
if (source == -1) {
break;
}
int destination = sc.nextInt();
graph.addEdge(source, destination);
}
graph.printGraph();
System.out.println("Enter the start index for BFS:");
graph.bfs(sc.nextInt());
System.out.println("Enter the start index for DFS:");
graph.dfs(sc.nextInt());
sc.close();
}
}