문제 링크 : programmers.co.kr/learn/courses/30/lessons/49994?language=cpp
<전체적인 알고리즘>
1. 입력으로 들어온 방향으로 움직인다.
2. 움직일 때 지나간 길을 체크해 둔다.
- 나는 해당 좌표에서 4방향의 길로 분류하여 체크를 하였다.
(현재 좌표에서 지나가야하는 방향 체크, 다음 좌표에서 지나온 방향 체크)
3. 처음 지나가는 길만 answer++해준다.
<전체 코드>
#include<iostream>
#include <string>
using namespace std;
bool check[15][15][4];
int dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int x = 5;
int y=5;
int answer = 0;
void moving(char c)
{
int d = 0;
if (c == 'U')d = 0;
else if (c == 'D')d = 2;
else if (c == 'R')d = 1;
else d = 3;
int nextx = x + dir[d][0];
int nexty = y + dir[d][1];
if (nextx < 0 || nexty <0 || nextx>10 || nexty>10)return;
if (!check[x][y][d])answer++;
check[x][y][d] = true; //좌표에서 d방향에 있는 길 방문처리
check[nextx][nexty][(d + 2) % 4] = true; //이동한 좌표에서 d반대 방향있는 길 방문처리
x = nextx;
y = nexty;
}
int solution(string dirs) {
for (int i = 0; i < dirs.size(); i++)
{
char c = dirs[i];
moving(c);
}
return answer;
}
궁금하신 점은 댓글에 남겨주시면 답변드리겠습니다.
반응형