-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.java
More file actions
140 lines (110 loc) · 2.89 KB
/
graph.java
File metadata and controls
140 lines (110 loc) · 2.89 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import java.util.LinkedList;
import java.util.Queue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Scanner;
class QueueUsingLL<T> {
private Node<T> front;
private Node<T> rear;
private int size;
public QueueUsingLL() {
front = null;
rear = null;
size = 0;
}
int size() {
return size;
}
boolean isEmpty() {
return size == 0;
}
T front() {
if (size == 0) {
return null;
}
return front.data;
}
void enqueue(T element) {
Node<T> newNode = new Node<>(element);
if (rear == null) {
front = newNode;
rear = newNode;
} else {
rear.next = newNode;
rear = newNode;
}
size++;
}
T dequeue() {
if (size == 0) {
return null;
}
T temp = front.data;
front = front.next;
if (size == 1) {
rear = null;
}
size--;
return temp;
}
}
class Node<T> {
public T data;
public Node<T> next;
public Node(T data) {
this.data = data;
next = null;
}
}
public class Solution {
public static void main(String[] args) throws NumberFormatException, IOException {
int n;
int e;
Scanner s = new Scanner(System.in);
n = s.nextInt();
e = s.nextInt();
int edges[][] = new int[n][n];
for (int i = 0; i < e; i++) {
int fv = s.nextInt();
int sv = s.nextInt();
edges[fv][sv] = 1;
edges[sv][fv] = 1;
}
printHelper(edges);
}
public static void printBFSHelper(int edges[][], int sv, boolean visited[]) {
QueueUsingLL<Integer> queueUsingLL = new QueueUsingLL<>();
queueUsingLL.enqueue(sv);
visited[sv] = true;
int n = edges.length;
while (!queueUsingLL.isEmpty()) {
int front = queueUsingLL.dequeue();
System.out.print(front+" ");
for (int i = 0; i < n; i++) {
if(edges[front][i] == 1 && !visited[i]){
queueUsingLL.enqueue(i);
visited[i] = true;
}
}
}
}
public static void printDFSHelper(int edges[][], int sv, boolean visited[]) {
System.out.println(sv);
visited[sv] = true;
int n = edges.length;
for (int i = 0; i < n; i++) {
if (edges[sv][i] == 1 && !visited[i]) {
printHelper(edges, i, visited);
}
}
}
public static void printHelper(int edges[][]) {
boolean visited[] = new boolean[edges.length];
for (int i = 0; i < edges.length; i++) {
if (!visited[i]) {
printBFSHelper(edges, i, visited);
}
}
}
}