문제: https://school.programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이:
class Solution {
int answer = Integer.MAX_VALUE;
public int solution(String begin, String target, String[] words) {
boolean[] visited = new boolean[words.length];
dfs(begin, target, words, visited, 0);
if(answer == Integer.MAX_VALUE) answer = 0; // 변환할 수 없는 경우
return answer;
}
public void dfs(String now, String target, String[] words, boolean[] visited, int time){
if(now.equals(target)){
answer = Math.min(answer, time);
return;
}
for (int i = 0; i < words.length; i++) {
if(visited[i]) continue;
String word = words[i];
int cnt = 0;
for (int j = 0; j < word.length(); j++) {
if(now.charAt(j) == word.charAt(j)) cnt++;
}
if(cnt == word.length() - 1){ // 1개 알파벳만 다른 경우
visited[i] = true;
dfs(word, target, words, visited, time+1);
visited[i] = false;
}
}
}
}
public class Main {
public static void main(String[] args){
Solution solution = new Solution();
int answer = solution.solution("hit", "cog", new String[]{"hot", "dot", "dog", "lot", "log"});
System.out.println("answer = " + answer);
}
}
'PS > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 석유 시추- JAVA(자바) (0) | 2024.05.23 |
---|---|
[프로그래머스] 가장 큰 수 - JAVA(자바) (1) | 2024.03.29 |
[프로그래머스] 등굣길 - JAVA(자바) (1) | 2023.11.17 |
[프로그래머스] 수식 최대화 - 자바 (0) | 2023.11.16 |
[프로그래머스] 불량 사용자 - JAVA(자바) (1) | 2023.11.14 |