-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPrintAdjList.java
More file actions
71 lines (52 loc) · 2.11 KB
/
Copy pathPrintAdjList.java
File metadata and controls
71 lines (52 loc) · 2.11 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
package src._1_basic;
import java.util.ArrayList;
import java.util.List;
/**
* <a href="https://www.geeksforgeeks.org/problems/print-adjacency-list-1587115620/1">Print adjacency list</a>
* <a href="https://www.youtube.com/watch?v=OsNklbh9gYI&t=637s&ab_channel=takeUforward">Build adjacency list</a>
*/
public class PrintAdjList {
public static void main(String[] args) {
int v = 5;
//int[][] edges = new int[][]{{0, 1}, {0, 4}, {4, 1}, {4, 3}, {1, 3}, {1, 2}, {3, 2}};
int[][] edges = new int[][]{{2, 3}, {4, 1}, {4, 0}, {2, 1}};
List<List<Integer>> adjList = createAdjList(v, edges);
printGraph(adjList);
}
public static List<List<Integer>> createAdjList(int v, int[][] edges) {
List<List<Integer>> adjList = new ArrayList<>(v);
for (int i = 0; i < v; i++) { // BIG MISTAKE I made. I didn't initialise. Initialise the list for each vertex.
adjList.add(new ArrayList<>());
}
for (int[] edge : edges) {
int src = edge[0]; // source node
int dst = edge[1]; // destination node
adjList.get(src).add(dst);
adjList.get(dst).add(src);
}
return adjList;
}
public static void printGraph(List<List<Integer>> adjList) {
for (int i = 0; i < adjList.size(); i++) {
for (int j = 0; j < adjList.get(i).size(); j++) {
System.out.print(adjList.get(i).get(j) + " ");
}
System.out.println();
}
}
// WRONG CODE. Here I didn't initialise the list for each vertex and hence got null pointer exception.
/*public List<List<Integer>> createAdjList(int V, int edges[][]) {
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < edges.length; i++) {
int src = edges[i][0];
int dst = edges[i][1];
System.out.println(src + " " + dst);
if (adjList.get(src) == null) {
adjList.add(src, new ArrayList<>());
} else {
adjList.get(src).add(dst);
}
}
return null;
}*/
}