6. Graph
这里收录的是真正的关于Graph data structure或者Graph Theory的题目.隐式图是一种算法/思想,不是真正关于Graph的,所以就收录在其它章节了BFS/DFS
Graph Valid Tree
Tree vs. Graph
class Solution {
/*
1.valid tree, N nodes can only have N - 1 edges
2.BFS to traversal all neighbors from a random node, check whether all nodes can be visited
3.need to build graph, Map<Integer, Set<Integer>> graph, key is node, value is set of neighbors
*/
public boolean validTree(int n, int[][] edges) {
if (edges == null || edges.length != n - 1) return false;
if (n == 1) return true;
Map<Integer, Set<Integer>> graph = buildGraph(edges);//key is node, value is set of neighbors
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
queue.offer(edges[0][0]);
while (!queue.isEmpty()) {
int node = queue.poll();
if (!visited.add(node)) continue;
for (int neighbor : graph.get(node)) {
queue.offer(neighbor);
}
}
return visited.size() == n;
}
private Map<Integer, Set<Integer>> buildGraph(int[][] edges) {
Map<Integer, Set<Integer>> graph = new HashMap<>();
for (int[] edge : edges) {
Set<Integer> neighbors = graph.getOrDefault(edge[0], new HashSet<>());
neighbors.add(edge[1]);
graph.put(edge[0], neighbors);
neighbors = graph.getOrDefault(edge[1], new HashSet<>());
neighbors.add(edge[0]);
graph.put(edge[1], neighbors);
}
return graph;
}
}Course Schedule
Course Schedule II
Is Graph Bipartite?
Best Meeting point
Last updated