๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ปTech/โ˜•Java

[Java] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋‹จ์–ด ๋ณ€ํ™˜

by _viper_ 2023. 10. 4.
๋ฐ˜์‘ํ˜•

๐Ÿ“„ ๋ฌธ์ œ

๋‹จ์–ด ๋ณ€ํ™˜

 

๐Ÿ’ก ํ’€์ด

BFS(๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰) ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ "begin" ๋ฌธ์ž์—ด์—์„œ "target" ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ์ตœ์†Œ ๋‹จ๊ณ„ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค.

 

import java.util.*;

class Solution {
    public int solution(String begin, String target, String[] words) {
        int answer = 0; // ์ตœ์†Œ ๋‹จ๊ณ„ ์ˆ˜๋ฅผ ์ €์žฅํ•  ๋ณ€์ˆ˜
        boolean[] visited = new boolean[words.length]; // ๋‹จ์–ด ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ถ”์ ํ•˜๋Š” ๋ฐฐ์—ด
        Queue<String> queue = new LinkedList<>(); // BFS ํƒ์ƒ‰์„ ์œ„ํ•œ ํ

        queue.offer(begin); // ์‹œ์ž‘ ๋‹จ์–ด๋ฅผ ํ์— ์ถ”๊ฐ€

        while (!queue.isEmpty()) { // ํ๊ฐ€ ๋น„์–ด์žˆ์ง€ ์•Š์€ ๋™์•ˆ ๋ฐ˜๋ณต
            int size = queue.size(); // ํ˜„์žฌ ๋ ˆ๋ฒจ์˜ ํ ํฌ๊ธฐ๋ฅผ ์ €์žฅ

            for (int i = 0; i < size; i++) {
                String current = queue.poll(); // ํ์—์„œ ํ˜„์žฌ ๋‹จ์–ด ์ถ”์ถœ

                if (current.equals(target)) { // ํ˜„์žฌ ๋‹จ์–ด๊ฐ€ ๋ชฉํ‘œ ๋‹จ์–ด์ธ ๊ฒฝ์šฐ
                    return answer; // ์ตœ์†Œ ๋‹จ๊ณ„ ์ˆ˜ ๋ฐ˜ํ™˜
                }

                for (int j = 0; j < words.length; j++) {
                    if (!visited[j] && canTransform(current, words[j])) {
                        // ๋‹จ์–ด ๋ฐฉ๋ฌธ ์—ฌ๋ถ€ ํ™•์ธ ๋ฐ ๋ณ€ํ™˜ ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ
                        visited[j] = true; // ๋‹จ์–ด๋ฅผ ๋ฐฉ๋ฌธ์œผ๋กœ ํ‘œ์‹œ
                        queue.offer(words[j]); // ํ์— ์ถ”๊ฐ€
                    }
                }
            }

            answer++; // ํ˜„์žฌ ๋ ˆ๋ฒจ์˜ ๋ชจ๋“  ๋‹จ์–ด๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ณ  ๋‹จ๊ณ„ ์ฆ๊ฐ€
        }

        return 0; // ๋ณ€ํ™˜ํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ
    }

    private boolean canTransform(String from, String to) {
        int diffCount = 0; // ๋ฌธ์ž ์ฐจ์ด๋ฅผ ๋‚˜ํƒ€๋‚ผ ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™”

        for (int i = 0; i < from.length(); i++) {
            if (from.charAt(i) != to.charAt(i)) {
                diffCount++; // ๋‹ค๋ฅธ ๋ฌธ์ž๊ฐ€ ๋ฐœ๊ฒฌ๋  ๋•Œ๋งˆ๋‹ค ์ฆ๊ฐ€
            }

            if (diffCount > 1) {
                return false; // ๋ฌธ์ž ์ฐจ์ด๊ฐ€ 1์„ ์ดˆ๊ณผํ•˜๋ฉด ๋ณ€ํ™˜ ๋ถˆ๊ฐ€๋Šฅ
            }
        }

        return diffCount == 1; // ๋ฌธ์ž ์ฐจ์ด๊ฐ€ 1์ด๋ฉด ๋ณ€ํ™˜ ๊ฐ€๋Šฅ, ๊ทธ ์™ธ์—” ๋ถˆ๊ฐ€๋Šฅ
    }
}