[ DFS 풀이 ]
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
map<pair<int,int>, vector<pair<int,int>>> m;
map<pair<int,int>, bool> vis;
map<pair<pair<int,int>, pair<int,int>>, bool> make;
int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int dy[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int ans=0;
void DFS(int Y, int X){
vis[{Y,X}] = true;
for(int i=0;i<m[{Y,X}].size();i++){
int ny = m[{Y,X}][i].first;
int nx = m[{Y,X}][i].second;
bool check = false;
if(make[{{Y,X}, {ny,nx}}] or make[{{ny,nx}, {Y,X}}]) check = true;
if(vis[{ny,nx}] and !check) ans++;
else if(vis[{ny,nx}]) continue;
make[{{Y,X}, {ny,nx}}] = true;
make[{{ny,nx}, {Y,X}}] = true;
DFS(ny, nx);
}
}
int solution(vector<int> arrows) {
int curX = 0;
int curY = 0;
for(int i=0;i<arrows.size();i++)
{
for(int j=0;j<2;j++)
{
int nx = curX + dx[arrows[i]];
int ny = curY + dy[arrows[i]];
bool flag = false;
m[{curY, curX}].push_back({ny, nx});
curY = ny;
curX = nx;
}
}
DFS(0,0);
return ans;
}
- 핵심(
방을 만드는 조건
)
이미 방문한 정점
을 다시 방문
하는 경우(vis
)
- 간선이
처음
만들어 지는 경우(make
)
- 예외 처리(
교차
)
- 교차시
정점
으로 체크할 수 없는 2개의 방
이 만들어짐
![](https://velog.velcdn.com/images%2Fneity16%2Fpost%2Fb56ba2ce-2caa-4947-a3d7-b83c1e26de18%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202021-03-19%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%201.49.02.png)
중간 지점
을 정점
으로 만들면 교차점을 검사
할 수 있음
--> 이동
을 2번으로 나누어서 진행
해야 함
![](https://velog.velcdn.com/images%2Fneity16%2Fpost%2F301d1926-98d2-412b-aeba-eb96a65ded25%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202021-03-19%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%201.49.08.png)
- 결과
: 재귀
로 해결해서 시간이좀 걸리지만 통과는 함 (반복문
으로 하면 더 빠름)
![](https://velog.velcdn.com/images%2Fneity16%2Fpost%2F26c04103-cea0-4335-a9f9-e6ae9f42a211%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202021-03-19%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%201.51.34.png)
[ 반복문 풀이 ]