
DFS 알고리즘인데 시작점의 사방만 확인한다.
문제를 대충읽고 전체 DFS 구현으로 작성해서 풀이에 실패했다.
이전에 DFS를 풀이할때는 주로 재귀로 했는데 스택을 사용한 풀이가 큐를 사용한 BFS와 유사해서 개인적으로 더 편하다.
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
int solution(vector<vector<string>> board, int h, int w) {
int answer = 0;
//DFS임
//재귀 말고 Stack으로 풀이함
//문제를 잘못 봄.
//DFS인데 시작점 사방만 확인함
int i;
vector<pair<int, int>> direction = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int current_x, current_y, next_x, next_y;
string color;
int n = board.size();
/*
vector<vector<bool>> visited(n, vector<bool>(n, false));
stack<pair<int, int>> st;
st.push({w, h});
visited[h][w] = true;
color = board[h][w];
while(!st.empty()){
current_x = st.top().first;
current_y = st.top().second;
st.pop();
cout << "현 위치 : " << current_x << ", " << current_y << " 현재 색깔 : " << color << "\n";
for(i = 0; i < direction.size(); i++){
next_x = current_x + direction[i].first;
next_y = current_y + direction[i].second;
if((next_x >= 0 && next_x < n) && (next_y >= 0 && next_y < n) && !visited[next_y][next_x] && (color == board[next_y][next_x])){
st.push({next_x, next_y});
visited[next_y][next_x] = true;
answer++;
}
}
}
*/
color = board[h][w];
for(i = 0; i < direction.size(); i++){
next_x = w + direction[i].first;
next_y = h + direction[i].second;
if((next_x >= 0 && next_x < n) && (next_y >= 0 && next_y < n) && (color == board[next_y][next_x])){
cout << next_x << ", " << next_y << ", " << color << "\n";
answer++;
}
}
return answer;
}