-
[프로그래머스]단어 변환 - JAVA문제풀이/프로그래머스 2021. 2. 28. 13:26
문제
programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수
programmers.co.kr
풀이
가장 짧은 변환 과정을 찾는 것이므로 BFS를 이용해서 탐색하였다.
Node를 만들어서 현재 word의 정보와 현재까지의 count를 저장해 주었고 이를 q에 넣어주었다.
현재 word가 다음에 변환할 수 있는 words를 찾아서 변환하였고, 현재 word가 target과 같아지면 현재 count를 반환하였다.
변환할 수 있는지 확인하는 방법은 현재 word와 words[i]를 한 자리씩 비교하여 다른 자리수가 하나라면 true를, 아니라면 false를 반환하도록 구현하였다.
코드
123456789101112131415161718192021222324252627282930313233343536373839404142434445import java.util.*;class Solution {public int solution(String begin, String target, String[] words) {boolean[] memo = new boolean[words.length];return bfs(begin, target, words, memo);}public int bfs(String begin, String target, String[] words, boolean[] memo) {Queue<Node> q = new LinkedList<>();q.offer(new Node(begin, 0));while(!q.isEmpty()) {Node node = q.poll();if(node.word.equals(target)) return node.count;for(int i = 0; i < words.length; i++) {//word가 words[i]로 변환될 수 있다면if(memo[i] == false && check(node.word, words[i])) {memo[i] = true;q.offer(new Node(words[i], node.count + 1));}}}return 0;}public boolean check(String s1, String s2) {int count = 0;for(int i = 0; i < s1.length(); i++) {if(s1.charAt(i) != s2.charAt(i)) count++;}if(count == 1) return true;return false;}public class Node {String word;int count;public Node(String word, int count) {this.word = word;this.count = count;}}}cs '문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스]여행경로 - JAVA (0) 2021.03.02 [프로그래머스]기둥과 보 설치 - JAVA (2) 2021.03.01 [프로그래머스]멀리 뛰기 - JAVA (0) 2021.02.27 [프로그래머스]게임 맵 최단거리 - JAVA (0) 2021.02.25 [프로그래머스]보석 쇼핑 - JAVA (0) 2021.02.24