graph
Edge list vs Adjacent list vs Adjacent matrix
// first way, more official
// but if there are redundant edges in input, might need to implement hashcode() and equal() methods to avoid add redundant nodes into neighbors. Kind of overkilling in an interview setting
class GraphNode
{
int val;
int status; // used for track visiting status in DFS
List<GraphNode> neighbor;
// ...
}
List<GraphNode> graph =...;
// second way, graph itself is more concise. But need additional data structures like Set<Integer> visited and Set<Integer> discovered to track dfs traverse status
Map<Integer, Set<Integer>> graph Build graph
Detect cycles inside undirected graph
Detect cycles inside directed graph
Last updated