GitHubSeob
C++ / 프로그래머스 / 단어 변환 본문
문제
https://school.programmers.co.kr/learn/courses/30/lessons/43163
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이
최소 과정을 찾기 위해 queue를 이용했다.
queue에는 바꾼 단어, 바꾼 횟수를 저장한다.
이중 for문을 이용해 비교할 단어를 고르고, 단어를 문자로 쪼개서 현재 단어와 비교한다.
최소 과정을 찾아야 하므로 이미 고른 단어는 다시 못 고르도록 visit벡터를 추가로 이용했다.
같지 않은 부분이 1개라면 바꿀 수 있는 단어다.
바꿀 수 있는 단어가 target이라면 cnt + 1 값을 return한다.
그 외의 경우는 방문표시를 하고 큐에 바꾼 단어, cnt + 1을 넣어 push한다.
코드
#include <string>
#include <vector>
#include <queue>
using namespace std;
int solution(string begin, string target, vector<string> words) {
int answer(0), cnt(0), idx(0), idx2(0), sub(0);
string str("");
queue<pair<string, int>>q;
vector<bool>visit(words.size(), false);
q.push({ begin,0 });
while (!q.empty()) {
str = q.front().first;
cnt = q.front().second;
q.pop();
for (idx = 0; idx < words.size(); ++idx) {
if (visit[idx] == false) {
sub = 0;
for (idx2 = 0; idx2 < words[idx].size(); ++idx2) {
if (words[idx][idx2] != str[idx2]) {
sub++;
}
}
if (sub == 1) {
if (words[idx] == target) {
return cnt + 1;
}
else {
visit[idx] = true;
q.push({ words[idx], cnt + 1 });
}
}
}
}
}
return 0;
}
'Programmers > Level 3' 카테고리의 다른 글
C++ / 프로그래머스 / 부대복귀 (0) | 2023.06.27 |
---|---|
C++ / 프로그래머스 / 디스크 컨트롤러 (0) | 2023.06.27 |
C++ / 프로그래머스 / 야근 지수 (0) | 2023.06.26 |
C++ / 프로그래머스 / 최고의 집합 (0) | 2023.06.26 |
C++ / 프로그래머스 / 연속 펄스 부분 수열의 합 (0) | 2023.06.26 |