mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
64 lines
1.4 KiB
Rust
64 lines
1.4 KiB
Rust
use std::collections::VecDeque;
|
|
|
|
struct Solution {}
|
|
impl Solution {
|
|
fn bfs(graph: &[Vec<i32>], visited: &mut [bool], u0: usize) {
|
|
let mut q = VecDeque::new();
|
|
q.push_back(u0);
|
|
visited[u0] = true;
|
|
|
|
while let Some(u) = q.pop_front() {
|
|
for v in (0..graph.len()).filter(|&v| graph[u][v] != 0) {
|
|
if visited[v] {
|
|
continue;
|
|
}
|
|
|
|
q.push_back(v);
|
|
visited[v] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn find_circle_num(is_connected: Vec<Vec<i32>>) -> i32 {
|
|
let mut visited = vec![false; is_connected.len()];
|
|
|
|
let mut count = 0;
|
|
for i in 0..is_connected.len() {
|
|
if visited[i] {
|
|
continue;
|
|
}
|
|
|
|
Solution::bfs(&is_connected, &mut visited, i);
|
|
count += 1;
|
|
}
|
|
|
|
count
|
|
}
|
|
}
|
|
|
|
fn main() {}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
// Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
|
|
// Output: 2
|
|
#[test]
|
|
fn example_1() {
|
|
assert_eq!(
|
|
Solution::find_circle_num(vec![vec![1, 1, 0], vec![1, 1, 0], vec![0, 0, 1]]),
|
|
2
|
|
);
|
|
}
|
|
|
|
// Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
|
|
// Output: 3
|
|
#[test]
|
|
fn example_2() {
|
|
assert_eq!(
|
|
Solution::find_circle_num(vec![vec![1, 0, 0], vec![0, 1, 0], vec![0, 0, 1]]),
|
|
3
|
|
);
|
|
}
|
|
}
|