[프로그래머스] 43163 단어 변환 - JAVA

2025. 5. 23. 17:49·알고리즘/문제풀이

[프로그래머스] 43163 단어 변환 - JAVA

문제

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

 

문제 분석

조건

  • 두 개의 단어 `begin`과 `target`이 주어지고, 단어를 한 글자씩 바꿔가며 target으로 변환해야 한다.
  • 단, 변환 과정에서 사용할 수 있는 단어는 `words` 배열 안에 존재해야만 한다.
  • 최소 몇 번의 변환으로 `begin` ->`target`으로 바꿀 수 있는지 출력.
  • `target`이 `words`에 없으면 변환 불가 → 0 리턴

풀이방법

  • 한번에 한 글자만 바뀌며, 바뀔 수 있는 단어가 정해져있고, 최소 횟수를 구하는 문제이므로 BFS를 통해 답을 구할 수 있다.
  • 즉 단어들을 그래프의 노드로 보고, 한 글자만 다른 단어들끼리 간선으로 연결 된 그래프라 생각하면 된다.
  • 굳이 그래프를 만들지 않고 탐색마다 변환 가능한 단어들을 구했으며, 방문 처리를 모든 단어를 Set에 넣고 방문 시 제외하는 형태로 구현하였다.

코드

import java.util.*;

class Node {
    private String word;
    private int count;

    public Node(String word, int count) {
        this.word = word;
        this.count = count;
    }

    public String getWord() {
        return word;
    }

    public int getCount() {
        return count;
    }
}

class Solution {
    static Set<String> visited;

    public int solution(String begin, String target, String[] words) {
        int answer = 0;
        visited = new HashSet<>();
        visited.addAll(Arrays.asList(words));
        if (!visited.contains(target)) {
            return answer;
        }
        answer = bfs(begin, target);
        return answer;
    }

    private int bfs(String begin, String target) {
        if (!visited.contains(target)) {
            return 0;
        }
        Deque<Node> q = new ArrayDeque<>();
        q.add(new Node(begin, 0));
        while (!q.isEmpty()) {
            Node now = q.pop();
            if (now.getWord().equals(target)) {
                return now.getCount();
            }
            List<String> nextList = getNextList(now.getWord());
            for (String word : nextList) {
                q.add(new Node(word, now.getCount() + 1));
                visited.remove(word);
            }
        }
        return 0;
    }

    private List<String> getNextList(String now) {
        List<String> nextList = new ArrayList<>();
        for (String next : visited) {
            int diffCount = 0;
            for (int i = 0; i < now.length(); i++) {
                if (now.charAt(i) != next.charAt(i)) {
                    diffCount++;
                }
                if (diffCount > 1) {
                    continue;
                }
            }
            if (diffCount == 1) {
                nextList.add(next);
            }
        }
        return nextList;
    }
}

시간복잡도

N: 단어 수, M: 단어 길이
각 단어에서 인접한 단어 탐색 시 O(N × M)
전체 BFS 탐색: O(N² × M)

 

+

문제에 접속했을 때 대놓고 BFS라고 적혀있어서 쉽게 풀었지만 알고리즘이 나와있지 않았다면 고민했을거같은 문제이다. 문자열을 이용한 BFS라 신박하고 재밌었다.

728x90
저작자표시 비영리 변경금지 (새창열림)
'알고리즘/문제풀이' 카테고리의 다른 글
  • [백준/BOJ] 16236 아기 상어 - JAVA
  • [백준/BOJ] 7576 토마토 - JAVA
  • [백준/BOJ] 1967 트리의 지름 - JAVA
  • [프로그래머스] 49189 가장 먼 노드 - JAVA
LIRI
LIRI
  • LIRI
    기록
    LIRI
  • 전체
    오늘
    어제
    • 분류 전체보기 (69) N
      • 블로그 꾸미기 (0)
      • Spring (6)
      • React (3)
      • CS (0)
      • 알고리즘 (53) N
        • 개념 (2)
        • 문제풀이 (50) N
      • Java (1)
      • DB (1)
      • log (4)
        • SSAFY (3)
        • 궁금 (1)
  • 블로그 메뉴

    • 홈
    • 방명록
  • 공지사항

  • 인기 글

  • 태그

    SSAFY 9기
    BOJ
    백준
    너비우선탐색
    dfs
    pccp모의고사
    Security
    JWT
    BFS
    그리디
    LV2
    Java
    ssafy 합격 후기
    비트마스킹
    Spring
    LIS
    불 끄기
    최장증가부분수열
    알고리즘
    springboot
    알고리즘 문제풀이
    프로그래머스
    리액트
    도대체왜
    Springsecurity
    dp
    lv3
    골드1
    SSAFY
    싸피
  • 최근 댓글

  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
LIRI
[프로그래머스] 43163 단어 변환 - JAVA
상단으로

티스토리툴바