반응형
문제
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.
예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -> "hot" -> "dot" -> "dog" -> "cog"와 같이 4단계를 거쳐 변환할 수 있습니다
두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.
문제풀이
class Solution {
boolean[] visited;
int answer = Integer.MAX_VALUE;
public void dfs(String begin, String target, String[] words, int count) {
if(begin.equals(target)) {
answer = Math.min(answer, count);
return;
} else {
for(int i = 0; i < words.length; i++) {
if(visited[i]) continue;
int cnt = 0;
for(int j = 0; j < begin.length(); j++) {
if(begin.charAt(j) == words[i].charAt(j)) {
cnt++;
}
}
if(cnt == begin.length() -1) {
visited[i] = true;
dfs(words[i], target, words, count + 1);
visited[i] = false;
}
}
}
}
public int solution(String begin, String target, String[] words) {
visited = new boolean[words.length];
dfs(begin, target, words, 0);
if(answer == Integer.MAX_VALUE) return 0;
return answer;
}
}
주의사항 (최소단계의 과정을 거쳐야 하기 때문에 target에 도착했을 때 최소값을 비교해줘야합니다.)
반응형
'알고리즘 > 프로그래머스 LV3' 카테고리의 다른 글
[프로그래머스] LV3 기지국 설치[JAVA] (0) | 2024.04.08 |
---|---|
[프로그래머스] LV3 단속카메라(JAVA) (0) | 2024.04.08 |
[프로그래머스] LV3 야근 지수(JAVA) (0) | 2024.04.02 |
[프로그래머스] LV3 이중우선순위큐(JAVA) (0) | 2024.04.02 |
[프로그래머스] LV3 정수 삼각형 (JAVA 풀이) (0) | 2024.04.01 |