티스토리 뷰
Algorithm/LeetCode
[LeetCode - Daily Challenge] 797. All Paths From Source to Target
Jaime.Lee 2021. 11. 29. 10:30Problem
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
Example 1:
Input: graph = [[1,2],[3],[3],[]]
Output: [[0,1,3],[0,2,3]]
Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Example 2:
Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
Example 3:
Input: graph = [[1],[]]
Output: [[0,1]]
Example 4:
Input: graph = [[1,2,3],[2],[3],[]]
Output: [[0,1,2,3],[0,2,3],[0,3]]
Example 5:
Input: graph = [[1,3],[2],[3],[]]
Output: [[0,1,2,3],[0,3]]
Constraints:
- n == graph.length
- 2 <= n <= 15
- 0 <= graph[i][j] < n
- graph[i][j] != i (i.e., there will be no self-loops).
- All the elements of graph[i] are unique.
- The input graph is guaranteed to be a DAG.
Solution
0~n-1까지의 값을 가지는 노드로 이뤄진 방향을 가진 비순환 그래프(DAG)가 주어질 때, 0에서 n-1까지 이동 가능한 모든 경로를 구하는 문제입니다.
전형적인 DFS 문제로 n-1 노드까지 접근했을 때 백트래킹 방식으로 다른 경로를 확인하면서 답을 구하면 됩니다.
import java.util.LinkedList;
import java.util.List;
public class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> result = new LinkedList<>();
List<Integer> path = new LinkedList<>();
path.add(0);
dfs(graph, 0, path, result);
return result;
}
private void dfs(int[][] graph, int index, List<Integer> path, List<List<Integer>> rst) {
if (index == graph.length - 1) {
rst.add(new LinkedList<>(path));
return;
}
for (int neighbor : graph[index]) {
path.add(neighbor);
dfs(graph, neighbor, path, rst);
path.remove(path.size() - 1);
}
}
}
Test
package io.lcalmsky.leetcode.all_paths_from_source_to_target;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
public void givenDirectedAcyclicGraph_whenFindAllPaths_thenCorrect() {
assertAll(
() -> test(new int[][]{{1, 2}, {3}, {3}, {}}, List.of(List.of(0, 1, 3), List.of(0, 2, 3))),
() -> test(new int[][]{{4, 3, 1}, {3, 2, 4}, {3}, {4}, {}},
List.of(List.of(0, 4), List.of(0, 3, 4), List.of(0, 1, 3, 4), List.of(0, 1, 2, 3, 4),
List.of(0, 1, 4))),
() -> test(new int[][]{{1}, {}}, List.of(List.of(0, 1))),
() -> test(new int[][]{{1, 2, 3}, {2}, {3}, {}},
List.of(List.of(0, 1, 2, 3), List.of(0, 2, 3), List.of(0, 3))),
() -> test(new int[][]{{1, 3}, {2}, {3}, {}}, List.of(List.of(0, 1, 2, 3), List.of(0, 3)))
);
}
private void test(int[][] given, List<List<Integer>> expected) {
// when
Solution solution = new Solution();
List<List<Integer>> actual = solution.allPathsSourceTarget(given);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode - Daily Challenge] 198. House Robber (0) | 2021.12.02 |
---|---|
[LeetCode - Daily Challenge] 85. Maximal Rectangle (0) | 2021.11.30 |
[LeetCode - Daily Challenge] 35. Search Insert Position (0) | 2021.11.27 |
[LeetCode - Daily Challenge] 53. Maximum Subarray (0) | 2021.11.26 |
[LeetCode - Daily Challenge] 106. Construct Binary Tree from Inorder and Postorder Traversal (0) | 2021.11.24 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Spring Boot JPA
- Spring Boot Tutorial
- Jackson
- 알고리즘
- spring boot jwt
- intellij
- QueryDSL
- 함께 자라기
- proto3
- 스프링부트
- 스프링 부트 애플리케이션
- 스프링 데이터 jpa
- 헥사고날 아키텍처
- leetcode
- gRPC
- JSON
- 스프링 부트
- Java
- r
- Linux
- 함께 자라기 후기
- spring boot app
- 클린 아키텍처
- 스프링 부트 회원 가입
- Spring Boot
- spring boot application
- @ManyToOne
- JPA
- 스프링 부트 튜토리얼
- Spring Data JPA
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
글 보관함