Created
October 14, 2021 08:08
-
-
Save vishalvrv9/5bf9a10ae070317e09abfc527308832c to your computer and use it in GitHub Desktop.
Java code to create adjacency list for Graph DSA problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Graph { | |
private enum GraphType { | |
DIRECTED, | |
UNDIRECTED | |
} | |
// util method to add edge | |
static void addEdge(List<List<Integer>> adjList, int from, int to, String graphType){ | |
adjList.get(from).add(to); | |
if("UNDIRECTED".equalsIgnoreCase(graphType)) | |
adjList.get(to).add(from); | |
} | |
public static void main(String []args){ | |
int noOfEdges = 5; | |
// initialization of adjacency list | |
List<List<Integer>> adjList = new ArrayList<>(noOfEdges); | |
for(int i = 0; i < noOfEdges; i++) | |
adjList.add(new ArrayList<>()); | |
// now you can add edges | |
addEdge(adjList, 1,2,"directed"); | |
addEdge(adjList, 1,3,"directed"); | |
addEdge(adjList, 2,4"directed"); | |
addEdge(adjList, 2,5,"directed"); | |
addEdge(adjList, 3,2,"directed"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment