mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(rs): add “547. Number of Provinces”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
f2bbcdd10a
commit
35252ff989
1 changed files with 64 additions and 0 deletions
64
problems/rs/number-of-provinces.rs
Normal file
64
problems/rs/number-of-provinces.rs
Normal file
|
@ -0,0 +1,64 @@
|
|||
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
|
||||
);
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue