GitHubSeob
C++ / 프로그래머스 / 공원 산책 본문
문제
https://school.programmers.co.kr/learn/courses/30/lessons/172928
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이
가는 길에 장애물이 있으면 왔던 길을 되돌아가고 다음 명령을 탐색한다.
park에서 'S'인 현재위치를 answer[0], answer[1]에 y, x값을 저장한다.
routes[idx][0]은 방향을, routes[idx][2]는 칸 수를 알려준다.
해당 방향으로 한칸 한 칸 가면서 주어진 맵의 좌표를 벗어나는지, 장애물이 있는지 판단한다.
없으면 기존 y, x값에 해당 방향으로 얼마나 움직였는지 더해준다.
코드
#include <string>
#include <vector>
using namespace std;
vector<int> solution(vector<string> park, vector<string> routes) {
vector<int> answer;
int y(0), x(0), idx(0), move(0), cnt(0);
char dir(' ');
for (y = 0; y < park.size(); ++y) {
for (x = 0; x < park[y].size(); ++x) {
if (park[y][x] == 'S') {
answer.push_back(y);
answer.push_back(x);
}
}
}
for (idx = 0; idx < routes.size(); ++idx) {
dir = routes[idx][0];
cnt = routes[idx][2] - '0';
move = cnt;
if (dir == 'N') {
y = -1;
x = 0;
}
else if (dir == 'S') {
y = 1;
x = 0;
}
else if (dir == 'W') {
y = 0;
x = -1;
}
else if (dir == 'E') {
y = 0;
x = 1;
}
for (cnt; cnt > 0; --cnt) {
if (answer[0] + y * cnt < 0 || park.size() <= answer[0] + y * cnt)
break;
if (answer[1] + x * cnt < 0 || park[0].size() <= answer[1] + x * cnt)
break;
if (park[answer[0] + y * cnt][answer[1]] == 'X')
break;
if (park[answer[0]][answer[1] + x * cnt] == 'X')
break;
}
if (cnt == 0) {
answer[0] += (y * move);
answer[1] += (x * move);
}
}
return answer;
}
'Programmers > Level 1' 카테고리의 다른 글
C++ / 프로그래머스 / 개인정보 수집 유효기간 (0) | 2023.06.21 |
---|---|
C++ / 프로그래머스 / 달리기 경주 (0) | 2023.06.20 |
C++ / 프로그래머스 / 크기가 작은 부분 문자열 (0) | 2023.06.20 |
C++ / 프로그래머스 / 삼총사 (0) | 2023.06.19 |
C++ / 프로그래머스 / 신고 결과 받기 (0) | 2022.03.08 |