new prolem solved

This commit is contained in:
Luca Lombardo
2024-02-21 18:32:37 +01:00
parent bffa5b871f
commit 3108b2e612
5 changed files with 112 additions and 2 deletions
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "is-bipartite"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+4
View File
@@ -0,0 +1,4 @@
# Idea
A graph is bipartite means that it can be divided into two sets of nodes, such that all edges connect a node from one set to a node from the other set. Let's call this set A and B. The simplest way to understand the idea is to say that this node in this graph cannot be in the same set as his neighbor.
We can create the two sets as EVEN and ODD. We start from a node and we put it in the EVEN set. Then we put all his neighbors in the ODD set. Then we put all their neighbors in the EVEN set, and so on. If we find a node that is already in a set, and we try to put it in the other set, then we have a conflict and the graph is not bipartite.
+39
View File
@@ -0,0 +1,39 @@
use std::collections::VecDeque;
struct Solution;
impl Solution {
fn dfs(graph: &Vec<Vec<i32>>, odd: &mut Vec<i32>, i: usize) -> bool {
if odd[i] != 0 {
return true;
}
let mut q = VecDeque::new();
odd[i] = -1; // this marks the node as visited
while q.len() > 0 {
let i = q.pop_front().unwrap();
// go through all the neighbors
for &nei in &graph[i] {
if odd[i] == odd[nei as usize] {
return false;
}
else if odd[nei as usize] == 0 {
q.push_back(nei as usize);
odd[nei as usize] = -odd[i];
}
}
}
return true;
}
pub fn is_bipartite(graph: Vec<Vec<i32>>) -> bool {
let mut odd = vec![0; graph.len()]; // map node i to odd=1, even=-1
for i in 0..graph.len() {
if !Self::dfs(&graph, &mut odd, i) {
return false;
}
}
return true;
}
}