-
797. All Paths From Source to TargetAlgorithm/java tip 2021. 3. 20. 23:20
leetcode.com/problems/all-paths-from-source-to-target/
class Solution { /* - node i direct to nodes in graph[i] - find all paths from node 0 to node n-1 //strategy 1. bfs > q 2. dfs > st //process 1. input 2. process mat[i][j] = 1 -> node i -> node j graph[0] = [1, 2] graph[1] = [3] graph[2] = [3] graph[3] = [] */ int start, end, len; boolean[] visit; List<List<Integer>> ans = new ArrayList<>(); public List<List<Integer>> allPathsSourceTarget(int[][] graph) { len = graph.length; start = 0; end = len - 1; visit = new boolean[len]; dfs(graph, 0, new ArrayList<Integer>()); return ans; } public void dfs(int[][] graph, int cur, List<Integer> path) { // already visit if(visit[cur]) { return; } visit[cur] = true; path.add(cur); if(cur == end) { ans.add(new ArrayList<Integer>(path)); } //adjacent node for(int adj : graph[cur]) { if(!visit[adj]) { dfs(graph, adj, path); } } visit[cur] = false; path.remove(path.size()-1); } }
'Algorithm > java tip' 카테고리의 다른 글
1387. Sort Integers by The Power Value (0) 2021.03.21 1557. Minimum Number of Vertices to Reach All Nodes (0) 2021.03.20 98. Validate Binary Search Tree (0) 2021.03.14 21. Merge Two Sorted Lists (0) 2021.03.13 530. Minimum Absolute Difference in BST (0) 2021.03.13