[Programmers] 단어 변환 (Java)

오태호·2022년 11월 20일
0

프로그래머스

목록 보기
19/56
post-thumbnail

1.  문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/43163

2.  문제

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다.

    1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.
    2. words에 있는 단어로만 변환할 수 있습니다.
예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -> "hot" -> "dot" -> "dog" -> "cog"와 같이 4단계를 거쳐 변환할 수 있습니다.
두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.

3.  제한사항

  • 각 단어는 알파벳 소문자로만 이루어져 있습니다.
  • 각 단어의 길이는 3 이상 10 이하이며 모든 단어의 길이는 같습니다.
  • words에는 3개 이상 50개 이하의 단어가 있으며 중복되는 단어는 없습니다.
  • begin과 target은 같지 않습니다.
  • 변환할 수 없는 경우에는 0를 return 합니다.

입출력 예

4.  소스코드

import java.util.*;

class Solution {
    static HashSet<String> candidate;
	public static int solution(String begin, String target, String[] words) {
		candidate = new HashSet<>();
		for(String word : words) candidate.add(word);
		if(!candidate.contains(target)) return 0;
		return bfs(begin, target);
	}
	
	static int bfs(String begin, String target) {
		Queue<Word> words = new LinkedList<Word>();
		HashSet<String> visited = new HashSet<String>();
		words.offer(new Word(begin, 0));
		visited.add(begin);
		int time = 0;
		while(!words.isEmpty()) {
			Word cur = words.poll();
			if(cur.word.equals(target)) {
				time = cur.count;
				break;
			}
			for(int alp = (int)'a'; alp < ((int)'a' + 26); alp++) {
				for(int index = 0; index < cur.word.length(); index++) {
					String left = cur.word.substring(0, index), right = cur.word.substring(index + 1, cur.word.length());
					String temp = left + (char)alp + right;
					if(candidate.contains(temp) && !visited.contains(temp)) {
						visited.add(temp);
						words.offer(new Word(temp, cur.count + 1));
					}
				}
			}
		}
		return time;
	}
	
	static class Word {
		String word;
		int count;
		public Word(String word, int count) {
			this.word = word;
			this.count = count;
		}
	}
}

5. 접근

  • words에 있는 단어들로만 변환이 가능하기 때문에 target이 words에 존재하지 않는다면 target으로 변환할 수 없으므로 그러한 경우에는 위 제한사항에 따라 0을 반환합니다.
  • 그렇지 않다면 BFS를 통해 begin의 각 알파벳들을 a부터 z까지 변경해보고 해당 알파벳이 words에 있다면 다음 탐색을 위해 몇 번 변환하였는지 횟수와 함께 Queue에 넣습니다.
  • 현재 탐색하는 단어가 target과 같다면 해당 횟수를 반환하고 Queue가 비워질 때까지 target과 같은 단어가 등장하지 않는다면 0을 반환합니다.
profile
자바, 웹 개발을 열심히 공부하고 있습니다!

0개의 댓글