LeetCode/problems/rs/number-of-provinces.rs
Matej Focko 35252ff989
problems(rs): add “547. Number of Provinces”
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-06-04 13:22:20 +02:00

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
);
}
}