티스토리 뷰

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

using namespace std;

int solution(string begin, string target, vector<string> words) {
    int answer = 0;
    vector<vector<int>> wordmap;
    int location = -1;

    words.insert(words.begin(), begin);
    wordmap.resize(words.size());
    for(int i = 0; i < words.size(); i++) {
        if(words[i] == target) {
            location = i;
            break;
        }
    }
    if(location == -1)
        return 0;

    for(int i = 0; i < words.size(); i++) {
        for(int j = 0; j < words.size(); j++) {
            int count = 0;
            for(int k = 0; k < words[0].length(); k++) {
                if(words[i].at(k) != words[j].at(k))
                    count++;
            }
            if(count == 1)
                wordmap[i].push_back(j);
        }
    }

    queue<int> q;
    vector<int> chk;

    chk.resize(wordmap.size());
    q.push(0);
    while(!q.empty()) {
        int front = q.front();
        q.pop();

        for(int i = 0; i < wordmap[front].size(); i++) {
            if(chk[wordmap[front][i]] == 0) {
                q.push(wordmap[front][i]);
                chk[wordmap[front][i]] = chk[front] + 1;
            }
        }
    }

    answer = chk[location];
    return answer;
}

처음 생각한 풀이는 한 글자를 node로 하고 각 글자가 같은 단어에 들어있으면 edge로 연결하는 그래프를 만드는 거였다. 그러나 같은 글자가 여러 단어에 걸쳐 나오고, 한 단어에 같은 글자가 두 번 이상 나올 수 있다. 이 때 글자를 node로 쓰면 어떤 edge가 찾고자 하는 경로로 가는 edge인지 판단하기 어렵지 싶었다.
다음으로 떠올린게 단어를 node로 쓰는 방법이다. 이러면 BFS로 경로의 길이를 저장하여 풀 수 있다. 오류가 한 번 났는데 한 글자 차이나는 단어끼리 연결한다는 걸 한 글자 일치하는 단어끼리 연결해서 그랬다.

'프로그래밍 > 문제풀이' 카테고리의 다른 글

[BOJ] 10844 쉬운 계단 수  (0) 2020.02.27
[BOJ] 9465 스티커  (0) 2020.02.21
[프로그래머스] 숫자 야구  (0) 2020.02.11
[BOJ] 1260 DFS와 BFS  (0) 2020.02.03
[BOJ] 11724 연결 요소의 개수  (0) 2020.02.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함