문제
797. All Paths From Source to Target
- 주어진 그래프에서 0번째 노드부터 n-1번째 노드까지의 모든 경로를 찾는 문제
해결 방법
최종 코드
class Solution {
public static List<List<Integer>> pathResult = new ArrayList<>();
public static int goal;
public static void dfs(int x, int[][] graph, ArrayList<Integer> path){
path.add(x);
if(x == goal){
pathResult.add(new ArrayList<>(path));
path.remove(path.size() - 1);
return;
}
for(int i = 0; i < graph[x].length; i++){
int y = graph[x][i];
dfs(y, graph, new ArrayList<>(path));
}
path.remove(path.size() - 1);
}
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
pathResult.clear();
visited = new boolean[graph.length];
goal = graph.length - 1;
ArrayList<Integer> path = new ArrayList<>();
dfs(0, graph, path);
return pathResult;
}
}
문제
단어 변환
- 단어를 변환할 수 있는 최소단계 구하기
해결 방법
int diff = 0;
for (int j = 0; j < begin.length(); j++) {
if (begin.charAt(j) != words[i].charAt(j)) diff++;
}
최종 코드
class Solution {
public static int min = Integer.MAX_VALUE;
public static void dfs(String begin, String target, String[] words, boolean[] visited, int count){
if(begin.equals(target)){
if(min > count) min = count;
return;
}
for(int i = 0; i<words.length; i++){
if(!visited[i]){
int diff = 0;
for(int j = 0; j<begin.length(); j++){
if(begin.charAt(j) != words[i].charAt(j)) diff++;
}
if(diff == 1){
visited[i] = true;
dfs(words[i], target, words, visited, count+1);
visited[i] = false;
}
}
}
}
public int solution(String begin, String target, String[] words) {
boolean exists = false;
for (String word : words) {
if (word.equals(target)) {
exists = true;
break;
}
}
if (!exists) return 0;
boolean[] visited = new boolean[words.length];
dfs(begin, target, words, visited, 0);
if(min == Integer.MAX_VALUE) return 0;
return min;
}
}