728x90
https://school.programmers.co.kr/learn/courses/30/lessons/43163
[ํด๊ฒฐ์ฑ ]
๋จ์ด๊ฐ 1๊ฐ ์ฐจ์ด๋๋ ๋จ์ด๋ฅผ ์ฐพ์์ BFS๋ฅผ ๊ณ์ ๋๋ฆฐ๋ค.
์ด๋ ํ์ count๋ฅผ ๊ณ์ ์ฒดํฌํด๊ฐ๋ฉฐ ์ต์ count๊ฐ์ ๊ตฌํด์ผ ํ๋ค.
์ข ๋ฃ์กฐ๊ฑด์ ํ์ ๋จ์ด๋ฅผ ์ฐพ์์ ๋์ words๋ฐฐ์ด ๋์ ๋๋ฌํ์์๋ target๋จ์ด๋ฅผ ๋ชป๋ง๋ฌ์ ๊ฒฝ์ฐ๋ค.
[์์๋ ๊ฒ]
1) INT_MAX๋ limits.h๋ฅผ ์ ์ธํด์ค์ผ ํ๋ค.
2) ์ฌํ์์ ์ํด ๋ฐฉ๋ฌธ์ฒดํฌ ํ๋ค๊ฐ ํ์ด์ฃผ๋ ๋ถ๋ถ.
[์ฝ๋]
#include <string>
#include <vector>
#include <iostream>
#include <limits.h>
using namespace std;
int answer = INT_MAX;
int DFS(string begin, string target, vector<string> words, vector<bool> &isVisited, int searchCount){
//searchCount๊ฐ answer๋ณด๋ค ํฌ๋ฉด ํ์ ํ์ ์์
if(searchCount > answer) return answer;
//ํ์ํ๋ ๋จ์ด๊ฐ target์ด๋ ๊ฐ์ผ๋ฉด answer ๊ฐ ์
๋ฐ์ดํธํ๊ณ return
if(begin == target){
answer = searchCount;
cout << answer << " ";
return answer;
}
//๋จ์ด๊ฐ์๋งํผ ๋ฐ๋ณตํ๋ฉฐ ๋จ์ด ํ๋์ฉ ์ ํ
//๋ฐฉ๋ฌธํ์ ์๋ ๋จ์ด์ ํ
for(int i = 0; i < words.size(); i++){
if(isVisited[i]) continue;
//๋จ์ด 1๊ฐ ์ฐจ์ด๋๋์ง ์ฒดํฌ
int diffCount = 0;
for(int j = 0; j < words[i].length(); j++){
if(begin[j] != words[i][j]) diffCount++;
}
if(diffCount == 1){
cout << words[i] << " ";
//๋ฐฉ๋ฌธ์ฒดํฌ
isVisited[i] = true;
DFS(words[i], target, words, isVisited, searchCount+1);
//์ฌ๋ฐฉ๋ฌธ์ ์ํด ๋ฐฉ๋ฌธ์ฒดํฌ ํด์
isVisited[i] = false;
}
}
return answer;
}
int solution(string begin, string target, vector<string> words) {
vector<bool> isVisited(words.size(), false);
answer = DFS(begin, target, words, isVisited, 0);
return (answer == INT_MAX) ? 0 : answer;
}
728x90
'๐ Coding Test Study > Algorithm Problem' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++][Programmers][ํด์] ํฌ์ผ๋ชฌ (0) | 2023.05.15 |
---|---|
[C++][Programmers][DFS/BFS] ์ฌํ๊ฒฝ๋ก (0) | 2023.05.09 |
[C++][Programmers][DFS/BFS] ๋คํธ์ํฌ (0) | 2023.05.06 |
[C++][Programmers][DFS/BFS] ๊ฒ์ ๋งต ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2023.05.04 |
[C++][Programmers][DFS/BFS] ํ๊ฒ๋๋ฒ (0) | 2023.05.02 |