分享二分图检测的rust实现
来源:4-11 实现二分图检测
戴JAVA老师的小迷弟
2024-05-08
未看视频前自己的实现,一些命名风格可能不一样
#[derive(Debug, Clone, PartialEq)]
enum Colour {
Blue,
Green,
White
}
#[derive(Debug)]
pub struct BipartitionDetection {
graph: Graph,
visited: Vec<Colour>,
is_bipartite: bool,
}
impl BipartitionDetection {
pub fn new(graph: Graph) -> Self {
let v = graph.v();
let mut graph_dfs = Self {
graph,
visited: vec![White; v],
is_bipartite: true
};
for v in 0..v {
if graph_dfs.visited[v] == White {
if !graph_dfs.dfs(v, v) {
graph_dfs.is_bipartite = false;
break
}
}
}
graph_dfs
}
// 是否符合二分图规则
fn dfs(&mut self, v: usize, parent: usize) -> bool {
// 染色 颜色为父节点颜色的对立面
let counter_color = match self.visited[parent] {
Colour::Blue => {Colour::Green}
Colour::Green => {Colour::Blue}
White => {Colour::Blue}
};
self.visited[v] = counter_color;
for w in self.graph.adj(v as i32).iter() {
// 如果当前节点没有访问过则进行检测
if self.visited[*w] == White {
if !self.dfs(*w, v) {
return false;
}
} else {
// 如果已经遍历过了查看颜色是否与当前节点是相对的
if self.visited[*w] == self.visited[v] {
return false
}
}
}
true
}
pub fn is_bipartite(&self) -> bool {
self.is_bipartite
}
}
写回答
1回答
-
liuyubobobo
2024-05-08
感谢分享,继续加油!:)
00
相似问题