>> 문제설명
leetcode.com/problems/keys-and-rooms/
Keys and Rooms - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
> 0개 이상의 간선을 가진 단일 방향 그래프에서 모든 정점을 탐색할 수 있는지를 묻는 문제입니다.
> BFS, DFS 와 같은 그래프 탐색 알고리즘을 사용하여 모든 정점의 방문 여부를 체크합니다.
> Solution(BFS)
import java.util.Arrays;
import java.util.List;
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
LinkedList<Integer> openList = new LinkedList<>();
HashSet<Integer> isOpened = new HashSet<>();
isOpened.add(0);
openList.add(0);
while (!openList.isEmpty()){
int size = openList.size();
for(int i = 0; i < size; i++){
for(int room : rooms.get(openList.pollFirst())){
if(!isOpened.contains(room)){
openList.add(room);
isOpened.add(room);
}
}
}
}
return isOpened.size() == rooms.size() ? true : false;
}
}
728x90
반응형
'Algorithms > LeetCode DailyChallenge' 카테고리의 다른 글
[LeetCode] 966. Vowel Spellchecker / JAVA (0) | 2021.03.23 |
---|---|
[LeetCode] 869. Reordered Power of 2 / JAVA (0) | 2021.03.22 |
[LeetCode] 376. Wiggle Subsequence / JAVA (0) | 2021.03.18 |
[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee / JAVA (0) | 2021.03.16 |
[LeetCode] 1721. Swapping Nodes in a Linked List / JAVA (0) | 2021.03.14 |