
단순히 그래프 순회로 풀 수 있는 문제다. 각 단어를 그래프의 노드라고 보고 변환이 가능한 단어를 인접 노드로 생각한다. 그래서 처음에 문제를 시작할 때 인접 행렬을 생성하고 BFS나 DFS로 선회하면 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <queue> | |
#include <iostream> | |
using namespace std; | |
int adj[51][51]; | |
bool visited[51]; | |
queue<pair<int, int>> q; | |
bool check(string A, string B) { | |
int len = A.length(); | |
int diff = 0; | |
for (int i = 0; i < len; i++) { | |
if (A[i] != B[i]) { | |
diff++; | |
} | |
} | |
return diff == 1; | |
} | |
int find(vector<string> words, string target) { | |
int idx = -1; | |
for (int i = 0; i < words.size(); i++) { | |
if (words[i] == target) { | |
idx = i; | |
break; | |
} | |
} | |
return idx; | |
} | |
int solution(string begin, string target, vector<string> words) { | |
int answer = 0; | |
words.insert(words.begin(), begin); | |
int size = words.size(); | |
int target_idx = find(words, target); | |
if(target_idx == -1) { | |
return 0; | |
} | |
for (int i = 0; i < size; i++) { | |
cout << words[i] << endl; | |
for (int j = 0; j < size; j++) { | |
adj[i][j] = check(words[i], words[j]); | |
} | |
} | |
q.push({0, 0}); | |
visited[0] = true; | |
while(!q.empty()) { | |
int cur = q.front().first; | |
int dist = q.front().second; | |
q.pop(); | |
if(cur == target_idx) { | |
return dist; | |
} | |
for (int i = 0; i < size; i++) { | |
if (adj[cur][i] != 0 && !visited[i]) { | |
q.push({i, dist+1}); | |
visited[i] = true; | |
} | |
} | |
} | |
return 0; | |
} |
'PS > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 숫자 게임 (2) | 2022.10.05 |
---|---|
[프로그래머스] 단속카메라 (0) | 2022.10.04 |
[프로그래머스] 야근 지수 (2) | 2022.10.01 |
[프로그래머스] 최고의 집합 (0) | 2022.10.01 |
[프로그래머스] 섬 연결하기 (2) | 2022.01.06 |