풀이
0. 현재 -> 다음 경로가 유효한지 체크
1. 현재 -> 다음, 다음 -> 현재로 이동한 경로가 이미 있는지 확인
2-1. 없으면 {(현재, 다음), (다음, 현재)} 좌표를 저장하고 다음으로 이동
2-2. 있으면 저장하지 않고 다음으로 이동
3. 방문한 경로의 수를 반환
정답
#include <string>
#include <vector>
#include <set>
#include <iostream>
using namespace std;
bool checkWall(pair<int, int> next) {
if (next.first > 5 || next.first < -5
|| next.second > 5 || next.second < -5) {
return true;
}
return false;
}
int solution(string dirs) {
int answer = 0;
pair<int, int> current = {0, 0};
set<pair<pair<int, int>, pair<int, int>>> visitedPath;
for (char dir : dirs) {
pair<int, int> next = current;
if (dir == 'U') {
next.second = current.second + 1;
} else if (dir == 'D') {
next.second = current.second - 1;
} else if (dir == 'R') {
next.first = current.first + 1;
} else if (dir == 'L') {
next.first = current.first - 1;
}
if (!checkWall(next)) {
if (visitedPath.find({next, current}) == visitedPath.end()
&& visitedPath.find({current, next}) == visitedPath.end()) {
visitedPath.insert({next, current});
visitedPath.insert({current, next});
}
current = next;
}
}
for (auto path: visitedPath) {
pair<int, int> current = path.first;
pair<int, int> next = path.second;
}
answer = visitedPath.size() / 2;
return answer;
}