[閒聊] 每日leetcode 75 - Day24 - 2

作者: yam276 ('_')   2025-07-07 16:59:32
841. Keys and Rooms
題目:
找一個圖每個點是否互相連通
思路:
題目給的是兩層 Vec 的鄰接表
所以我們就每次進房間 查鄰接表 然後進去每個房間
進過的房間做記號 看到記號直接退出節省效率
最後看記號表是否每個房間都去過了
Code:
impl Solution {
pub fn can_visit_all_rooms(rooms: Vec<Vec<i32>>) -> bool {
fn dfs(room: usize, rooms: &Vec<Vec<i32>>, visited: &mut Vec<bool>) {
if visited[room] {
return;
}
visited[room] = true;
for &key in &rooms[room] {
dfs(key as usize, rooms, visited);
}
}
let mut visited = vec![false; rooms.len()];
dfs(0, &rooms, &mut visited);
visited.into_iter().all(|v| v)
}
}

Links booklink

Contact Us: admin [ a t ] ucptt.com