作者yam276 (史萊哲林的優等生)
標題[閒聊] 每日leetcode 75 - Day24 - 2
時間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)
}
}
--
※ 發信站: 批踢踢實業坊(www.ptt-club.com.tw), 來自: 60.248.143.172 (臺灣)
※ 文章網址: https://www.ptt-club.com.tw/Marginalman/M.1751878774.A.1AC