面试中常见的图论问题
二分图问题:
LeetCode 785. Is Graph Bipartite?
这是一个直白的二分图问题:二分图问题,就是可否将图的所有节点分成两个集合,有连边两个点不在一个集合。
将二分图问题可以看成二染色问题,即使用两种颜色对图进行染色,相连的两个点,颜色不能相同。
解决办法:遍历染色
DFS+染色:
class Solution {
public boolean isBipartite(int[][] graph) {
// 染色状态; 0-未染色,1-蓝色,-1-红色
int[] colors = new int[graph.length];
for (int i = 0; i < colors.length; i++) {
if(colors[i]==0 && !dfs(i, 1, colors, graph)){
return false;
}
}
return true;
}
private boolean dfs(int v, int color, int[] colors, int[][] graph) {
colors[v]=color;
for(int adjV:graph[v]){
if(colors[adjV]==color) return false;
if(colors[adjV]==0 && !dfs(adjV, -color, colors, graph)){
return false;
}
}
return true;
}
}
也可以BFS+染色:
public class Solution {
public boolean isBipartite(int[][] graph) {
// 染色状态; 0-未染色,1-蓝色,-1-红色
int[] colors = new int[graph.length];
for (int i = 0; i < colors.length; i++) {
if(colors[i]==0 && graph[i].length>0){
colors[i] = 1;
Queue<Integer> q = new LinkedList<>();
q.offer(i);
while(!q.isEmpty()){
int curr = q.poll();
for(int adjV:graph[curr]){
if(colors[adjV]==0){
colors[adjV]=-colors[curr];
q.offer(adjV);
}
else if(colors[adjV]==colors[curr]) return false;
}
}
}
}
return true;
}
}
这道题加了点丰富的背景,但是很容易看出来还是一个二分图问题。据说这道题是今年字节跳动的笔试题
多了一点构建图。
DFS+染色:
public class Solution {
public boolean possibleBipartition(int N, int[][] dislikes) {
// 构建图
List<Integer>[] graph = new ArrayList[N+1];

本文探讨面试中常遇到的图论问题,包括二分图的染色策略,如LeetCode 785和886题的DFS与BFS解决方案;拓扑排序的应用,如207和210题的课程安排;以及并查集的运用,如解决684和547题的朋友圈问题。同时提到了图论的其他问题,如最短路和网络流。
最低0.47元/天 解锁文章
176万+

被折叠的 条评论
为什么被折叠?



