Graph Data Structure
Graph Data Structure
By Apna College
Note - There are 2 sections in this document
● Section 1 - Graph Codes (Page 1 - 24)
● Section 2 - Graph Assignments (page 25 - 30)
Graph Codes
Part1
BFS
import java.util.*;
while(!q.isEmpty()) {
int curr = q.remove();
if(!visited[curr]) {
System.out.print(curr+" ");
visited[curr] = true;
System.out.println();
}
public static void main(String args[]) {
/*
1 --- 3
/ | \
0 | 5 -- 6
\ | /
2 ---- 4
*/
int V = 7;
ArrayList<Edge> graph[] = new ArrayList[V];
createGraph(graph);
bfs(graph, V);
}
}
DFS
import java.util.*;
System.out.print(curr+" ");
visited[curr] = true;
for(int i=0; i<graph[curr].size(); i++) {
Edge e = graph[curr].get(i);
dfs(graph, e.dest, visited);
}
}
public static void main(String args[]) {
/*
1 --- 3
/ | \
0 | 5 -- 6
\ | /
2 ---- 4
*/
int V = 7;
ArrayList<Edge> graph[] = new ArrayList[V];
createGraph(graph);
All Paths
import java.util.*;
//For Youtube Lecture
public class PrintAllPaths {
static class Edge {
int src;
int dest;
public Edge(int s, int d) {
this.src = s;
this.dest = d;
}
}
public static void printAllPaths(ArrayList<Edge> graph[], int src, int tar, String
path, boolean vis[]) {
if(src == tar) {
System.out.println(path);
return;
}
}
public static void main(String args[]) {
int V = 7;
ArrayList<Edge> graph[] = new ArrayList[V];
createGraph(graph);
int src = 0;
int tar = 5;
boolean vis[] = new boolean[V];
vis[src] = true;
printAllPaths(graph, src, tar, ""+src, vis);
}
}
Part2
Cycle Detection (Undirected Graph)
import java.util.*;
return false;
}
//O(V+E)
public static boolean isCyclic(ArrayList<Edge>[] graph, boolean vis[]) {
for(int i=0; i<graph.length; i++) {
if(isCyclicUtil(graph, vis, i, -1)) {
return true;
}
}
return false;
}
*/
int V = 5;
ArrayList<Edge> graph[] = new ArrayList[V];
createGraph(graph);
//graph1 - true
static void createGraph(ArrayList<Edge> graph[]) {
for(int i=0; i<graph.length; i++) {
graph[i] = new ArrayList<>();
}
//graph2 - false
// static void createGraph(ArrayList<Edge> graph[]) {
// for(int i=0; i<graph.length; i++) {
// graph[i] = new ArrayList<>();
// }
//O(V + E)
public static boolean isCyclic(ArrayList<Edge>[] graph) {
boolean vis[] = new boolean[graph.length];
Topological Sorting
import java.util.*;
s.push(curr);
}
//O(V+E)
public static void topoSort(ArrayList<Edge> graph[]) {
boolean vis[] = new boolean[graph.length];
Stack<Integer> s = new Stack<>();
while(!s.isEmpty()) {
System.out.print(s.pop()+" ");
}
}
topoSort(graph);
}
}
Part3
@Override
public int compareTo(Pair p2) {
return this.path - p2.path;
}
}
public static int[] dijkstra(ArrayList<Edge> graph[], int src) {
PriorityQueue<Pair> pq = new PriorityQueue<>();
int dist[] = new int[graph.length];
boolean vis[] = new boolean[graph.length];
for(int i=0; i<dist.length; i++) {
if(i != src) {
dist[i] = Integer.MAX_VALUE;
}
}
pq.add(new Pair(src, 0));
while(!pq.isEmpty()) {
Pair curr = pq.remove();
if(!vis[curr.n]) {
vis[curr.n] = true;
}
}
}
return dist;
}
public static void main(String args[]) {
int V = 6;
ArrayList<Edge> graph[] = new ArrayList[V];
createGraph(graph);
int src = 0;
//O(V)
for(int i=0; i<graph.length-1; i++) {
//edges - O(E)
for(int j=0; j<graph.length; j++) {
for(int k=0; k<graph[j].size(); k++) {
Edge e = graph[j].get(k);
int u = e.src;
int v = e.dest;
int wt = e.wt;
if(dist[u] != Integer.MAX_VALUE && dist[u]+wt < dist[v]) {
dist[v] = dist[u] + wt;
}
}
}
}
Part4
//O(ElogE)
public static void primAlgo(ArrayList<Edge> graph[]) {
boolean vis[] = new boolean[graph.length];
PriorityQueue<Pair> pq = new PriorityQueue<>();
pq.add(new Pair(0, 0));
int cost = 0;
while(!pq.isEmpty()) {
Pair curr = pq.remove();
if(!vis[curr.v]) {
vis[curr.v] = true;
cost += curr.wt;
System.out.println(cost);
}
primAlgo(graph);
}
}
s.push(curr);
}
//Step2
ArrayList<Edge> transpose[] = new ArrayList[V];
for(int i=0; i<V; i++) {
transpose[i] = new ArrayList<Edge>();
}
//Step3
while(!s.isEmpty()) {
int curr = s.pop();
if(!vis[curr]) {
System.out.print("SCC : ");
dfs(transpose, vis, curr);
System.out.println();
}
}
}
kosaraju(graph, V);
}
}
Part5
To do : after Part1
You are given an m x n grid where each cell can have one of three values:
● 0 representing an empty cell,
● 1 representing a fresh orange, or
● 2 representing a rotten orange.
Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange
becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh
orange. If this is impossible, return -1.
Example 1
Input: grid = [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2
Input: grid = [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never
rotten, because rotting only happens 4-directionally.
Example 1
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
To do : after Part2
For example, the pair [0, 1], indicates that to take course 0 you have to first take
course 1.
Return true if you can finish all courses. Otherwise, return false.
Example 1
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you
should also have finished course 1. So it is impossible.
There is a directed graph of n nodes with each node labeled from 0 to n - 1. The
graph is represented by a 0-indexed 2D integer array graph where graph[i] is an
integer array of nodes adjacent to node i, meaning there is an edge from node i to
each node in graph[i].
A node is a terminal node if there are no outgoing edges. A node is a safe node if
every possible path starting from that node leads to a terminal node (or another
safe node).
Return an array containing all the safe nodes of the graph. The answer should be
sorted in ascending order.
Example 1
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of
them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
Example 2
Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
Practice online :
https://leetcode.com/problems/find-eventual-safe-states/description/
To do : after Part3
You are also given three integers src, dst, and k, return the cheapest price from src
to dst with at most k stops. If there is no such route, return -1.
Example 1
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst
= 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost
100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses
2 stops.
Example 2
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost
100 + 100 = 200.
To do : after Part4
Qs - Remove Max Number of Edges to Keep Graph Fully Traversable
(Microsoft/Google/Uber)
Alice and Bob have an undirected graph of n nodes and three types of edges:
Return the maximum number of edges you can remove, or return -1 if Alice and
Bob cannot fully traverse the graph.
Example 1
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be
fully traversable by Alice and Bob. Removing any additional edge will not make it
so. So the maximum number of edges we can remove is 2.
Example 2
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
Output: 0
Explanation: Notice that removing any edge will not make the graph fully
traversable by Alice and Bob.
Practice online :
https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-full
y-traversable/description/
To do : after Part5
Example 1
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.
Example 2
Input: n = 2, connections = [[0,1]]
Output: [[0,1]]
Practice online :
https://leetcode.com/problems/critical-connections-in-a-network/description/