[프로그래머스] 단어 변환(C++)

2025. 5. 26. 20:31·개발/알고리즘

문제 링크

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

코드 구현

#include <iostream>
#include <string>
#include <vector>
#include <queue>

using namespace std;

bool IsNeighbor(const string& a, const string& b)
{
    // 두 단어를 비교하여 하나만 단어가 다른 경우를 찾음
    int diff = 0;
    for (int i = 0; i < a.size(); ++i)
    {
        if (a[i] != b[i]) diff++;
        if (diff > 1) return false;
    }

    return true;
}

int solution(string begin, string target, vector<string> words) 
{
    int n = words.size();

    vector<bool> visited(n, false);
    queue<pair<string, int>> q;

    // 현재 단어와 카운트를 큐에 삽입
    q.push({ begin, 0 });
    
    // bfs 순회
    while (!q.empty())
    {
        pair<string, int> now = q.front();

        string currentStr = now.first;
        int count = now.second;

        q.pop();

        if (currentStr == target) return count;

        // 방문하지 않고 단어가 하나만 다른 단어를 큐에 삽입
        for (int i = 0; i < n; ++i)
        {
            if (!visited[i] && IsNeighbor(currentStr, words[i]))
            {
                visited[i] = true;
                q.push({ words[i], count + 1 });
            }
        }
    }

    return 0;
}

 

 

해결 방법

  • 가장 짧은 변환 과정을 찾으므로 bfs 이용
  • words 안에 있는 단어 중 한 번에 하나의 알파벳만 바꿀 수 있으므로 알파벳이 하나만 다른 단어들을 다음에 순회할 노드라고 생각하고 큐에 삽입
  • 큐를 순회하며 카운트 값 증가

'개발 > 알고리즘' 카테고리의 다른 글

[백준] 7576번: 토마토(C++)  (1) 2025.05.24
[백준] 1967번: 트리의 지름(C++)  (1) 2025.05.16
[프로그래머스] 가장 먼 노드(C++)  (1) 2025.05.15
[프로그래머스] 길 찾기 게임(C++)  (2) 2025.05.13
[백준] 회의실 배정(C++)  (1) 2025.05.12
'개발/알고리즘' 카테고리의 다른 글
  • [백준] 7576번: 토마토(C++)
  • [백준] 1967번: 트리의 지름(C++)
  • [프로그래머스] 가장 먼 노드(C++)
  • [프로그래머스] 길 찾기 게임(C++)
Majangnan
Majangnan
  • Majangnan
    개발 모코코
    Majangnan
  • 전체
    오늘
    어제
    • 분류 전체보기 (63) N
      • 개발 (62) N
        • C# (10)
        • SQL (3)
        • Unity (8)
        • Unreal (10)
        • C++ (2)
        • Server (1)
        • DX11 (8)
        • 알고리즘 (19) N
  • 블로그 메뉴

    • 홈
    • 방명록
    • 깃허브
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Unity
    MAC
    3dlight
    dx3d
    프로그래머스
    c++
    sql
    알고리즘
    백준
    Mecanim
    코딩테스트
    C#
    언리얼
    슈팅게임
    블루프린트
    UnReal
    DX11
    DirectX11
    상속
    blueprint
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Majangnan
[프로그래머스] 단어 변환(C++)
상단으로

티스토리툴바