프로그래머스 단어 변환
Updated:
문제 링크 : 프로그래머스 https://programmers.co.kr/learn/courses/30/lessons/43163?language=java
import java.util.*;
public class Solution {
private String[] map;
private boolean[] visited;
private int targetIndex;
private int answer = Integer.MAX_VALUE;
public int solution(String begin, String target, String[] words) {
map = words.clone();
// words 문자 배열에 target이 없으면 0 return
if (!isContain(words, target)) {
return 0;
}
// words 배열에서 target이 몇번째인지 targetIndex에 저장
for (int i = 0; i < map.length; i++) {
if (words[i].equals(target)) {
targetIndex = i;
break;
}
}
//begin과 map[i]가 문자 하나만 다르면 bfs 스타트
for (int i = 0; i < map.length; i++) {
if (isOnlyOneDifferentCharacter(begin, map[i])) {
visited = new boolean[map.length];
visited[i] = true;
bfs(i);
}
}
return answer;
}
private void bfs(int index) {
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(index, 1));
while (!queue.isEmpty()) {
Point point = queue.poll();
if (map[point.index].equals(map[targetIndex])) {
answer = Math.min(answer, point.depth);
return;
}
for (int i = 0; i < map.length; i++) {
// 방문 안했고 하나만 다르면
if (!visited[i] && isOnlyOneDifferentCharacter(map[point.index], map[i])) {
// queue에 add
visited[i] = true;
queue.add(new Point(i, point.depth + 1));
}
}
}
}
//문자 하나만 다른지 체크하는 함수
private boolean isOnlyOneDifferentCharacter(String now, String word) {
int count = 0;
for (int i = 0; i < now.length(); i++) {
if (now.charAt(i) != word.charAt(i)) {
count++;
}
}
return count == 1;
}
private boolean isContain(String[] words, String target) {
for (String word : words) {
if (word.equals(target)) {
return true;
}
}
return false;
}
private class Point {
//현재 인덱스
private int index;
//몇번째 진행중인가
private int depth;
public Point(int index, int depth) {
this.index = index;
this.depth = depth;
}
}
}
Leave a comment