Leetcode 261 Graph Valid Tree
Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
first, let’s ask ourselves, what make a gralh also a tree? the answer is an acyclic graph is a valid tree.
so we need to detect if current contains cycle.
and also, in this case, we need to check every node is connected.
due to this problem is undirected, so we convert the input as adjacent matrix to represent the graph. and we use hashmap to store node-node pair, so this hashmap used for check if we already visited this edge or not.
so the code can be divide into following parts:
//map construct using adjancent list
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjacencyList.add(new ArrayList<>());
}
for (int[] edge: edges) {
adjacencyList.get(edge[0]).add(edge[1]);
adjacencyList.get(edge[1]).add(edge[0]); //because it is undirected graph
}
//checking part., use hashmap for checking and stack for dfs. if we meet the edge we used to travel before, then it is a circle. and besides, it is importasnt to check if the size of hashmap is n or not because it is required that we have to contained every node in a graph, otherwise, the whole nodes maybe more than 1 graph.
Map<Integer, Integer> parent = new HashMap<>();
parent.put(0, -1);
Stack<Integer> stack = new Stack<>(); //stack will uses for dfs
stack.push(0);
//we do dfs while at the same time, we constrcut the parent hashmap
while (!stack.isEmpty()) {
int node = stack.pop();
for (int neighbor: adjacencyList.get(node)) { //for evert node that connext to current node
if (parent.get(node) == neighbor) { //this means we used to go from neighbor to node before
continue; //we continue? because we can find another way(which means change to another neighbor)
}
if (parent.containsKey(neighbor)) { //this means we used to go frim node to neighhbor before, and this is not right, it means we defintely have a circle
return false;
}
stack.push(neighbor);//push one of the neighbor of current node in stack
parent.put(neighbor, node);
}
}
return parent.size() == n;//parent is n means every node is connect to someother node

浙公网安备 33010602011771号