지나다니는 길을 'O', 장애물을 'X'로 나타낸 직사각형 격자 모양의 공원에서 로봇 강아지가 산책을 하려합니다. 산책은 로봇 강아지에 미리 입력된 명령에 따라 진행하며, 명령은 다음과 같은 형식으로 주어집니다.
["방향 거리", "방향 거리" … ]
예를 들어 "E 5"는 로봇 강아지가 현재 위치에서 동쪽으로 5칸 이동했다는 의미입니다. 로봇 강아지는 명령을 수행하기 전에 다음 두 가지를 먼저 확인합니다.
주어진 방향으로 이동할 때 공원을 벗어나는지 확인합니다.
주어진 방향으로 이동 중 장애물을 만나는지 확인합니다.
위 두 가지중 어느 하나라도 해당된다면, 로봇 강아지는 해당 명령을 무시하고 다음 명령을 수행합니다.
공원의 가로 길이가 W, 세로 길이가 H라고 할 때, 공원의 좌측 상단의 좌표는 (0, 0), 우측 하단의 좌표는 (H - 1, W - 1) 입니다.
공원을 나타내는 문자열 배열 park, 로봇 강아지가 수행할 명령이 담긴 문자열 배열 routes가 매개변수로 주어질 때, 로봇 강아지가 모든 명령을 수행 후 놓인 위치를 [세로 방향 좌표, 가로 방향 좌표] 순으로 배열에 담아 return 하도록 solution 함수를 완성해주세요.
입출력 예 #1
입력된 명령대로 동쪽으로 2칸, 남쪽으로 2칸, 서쪽으로 1칸 이동하면 [0,0] -> [0,2] -> [2,2] -> [2,1]이 됩니다.
입출력 예 #2
입력된 명령대로라면 동쪽으로 2칸, 남쪽으로 2칸, 서쪽으로 1칸 이동해야하지만 남쪽으로 2칸 이동할 때 장애물이 있는 칸을 지나기 때문에 해당 명령을 제외한 명령들만 따릅니다. 결과적으로는 [0,0] -> [0,2] -> [0,1]이 됩니다.
입출력 예 #3
처음 입력된 명령은 공원을 나가게 되고 두 번째로 입력된 명령 또한 장애물을 지나가게 되므로 두 입력은 제외한 세 번째 명령만 따르므로 결과는 다음과 같습니다. [0,1] -> [0,0]
#include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
bool check_movable(int cur_i, int cur_j, char op, int n, vector<string> park);
vector<int> move(int cur_i, int cur_j, char op, int n);
bool check_movable(int cur_i, int cur_j, char op, int n, vector<string> park) {
map<char, vector<int>> move = {
{'N', {-1, 0}},
{'S', {1, 0}},
{'E', {0, 1}},
{'W', {0, -1}}
for(int i=0; i<n; i++) {
cur_i += move[op][0];
cur_j += move[op][1];
if(cur_i == park.size() || cur_i < 0 || cur_j <0 || cur_j == park[0].size()) return false;
else if(park[cur_i][cur_j] == 'X') return false;
}
return true;
}
vector<int> move(int cur_i, int cur_j, char op, int n) {
map<char, vector<int>> move = {
{'N', {-n, 0}},
{'S', {n, 0}},
{'E', {0, n}},
{'W', {0, -n}}
};
cur_i += move[op][0];
cur_j += move[op][1];
vector<int> cur_pos = {cur_i, cur_j};
return cur_pos;
}
vector<int> solution(vector<string> park, vector<string> routes) {
vector<int> answer;
// 시작위치 찾기
int si = 0; int sj = 0;
for(int i=0; i<park.size(); i++) {
for(int j=0; j<park[0].size(); j++) {
if(park[i][j] == 'S') {
si = i;
sj = j;
break;
}
}
}
int cur_i=si; int cur_j=sj; // 현재위치 초기화
// 이동 가능 여부 체크 및 이동
for(int i=0; i<routes.size(); i++) {
char op = routes[i][0]; // 방향 파싱
string str(1, routes[i][2]); // 이동칸수 파싱
int n = stoi(str);
if(check_movable(cur_i, cur_j, op, n, park)) {
vector<int> moved = move(cur_i, cur_j, op, n);
// 이동
cur_i = moved[0];
cur_j = moved[1];
cout << cur_i << ' ' << cur_j << endl;
}
else continue; // 이동불가 시 다음 명령으로 이동
}
return {cur_i, cur_j};
}
str.find(delimiter)
로 구분자(delimiter)의 인덱스를 찾고 substring(start_idx, offset)
으로 부분 문자열 나눈다.
#include <string>
#include <iostream>
using namespace std;
string str = "abc def";
size_t pos = str.find(' ');
if (pos != std::string::npos) {
string substr1 = str.substr(0, pos); // "abc"
string substr2 = str.substr(pos+1); // "def"
}
else {
std::cout << "Not found" << std::endl;
}
npos는 none position의 약자로 pos를 못찾았음을 의미.
size_t는 양의 정수를 나타내는 typedef로 unsigned의 역할을 함. 주로 배열의 인덱스나 문자열의 길이 등 양의 값만 존재 시 사용.
str.substring(start_idx, offset)
은 start_idx부터 offset만큼 부분문자열 리턴.
두가지 방법이 있다.
1. find()
와 substr()
을 활용해 구현.
2. sstream을 활용.
1. find() & substr() 활용
#include <string>
#include <vector>
using namespace std;
string str = "abc def ghi"; // 타겟 문자열
string delimiter = " "; // 구분자
vector<string> result; // 구분된 문자열 저장 벡터
size_t start = 0; // 관찰할 시작인덱스
size_t end = str.find(delimiter); // 관찰할 종료인덱스
while(end != string::npos) { // 관찰할 종료인덱스가 존재하는 동안
result.push_back(str.substr(start, end-start)); // 부분문자열 파싱하여 벡터에 삽입
start = end+1; //시작 위치 업데이트
end = str.find(delimiter, start); // start부터 문자열 끝까지 중 처음으로 나오는 delimiter의 인덱스 탐색하여 종료 인덱스 업데이트
}
result.push_back(str.substr(start)); // 마지막 원소 삽입
2. sstream 활용
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
vector<string> split(const string& str, char delimiter) {
vector<string> tokens; // 정답 저장 벡터
std::stringstream ss(str); // 타겟 문자열을 stream객체로 변환
std::string item; // 분리한 문자열을 담을 변수
while (std::getline(ss, item, delimiter)) { // ss 객체를 delimiter 기준으로 구분한 item이 존재하는 동안
tokens.push_back(item); // 벡터에 item 삽입
}
return tokens;
}
int main() {
std::string data = "apple,banana,orange";
std::vector<std::string> result = split(data, ',');
for (const auto& s : result) {
std::cout << s << std::endl;
}
return 0;
}
stringstream: 문자열을 스트림처럼 쓸 수 있게 해주는 객체 차례로 읽거나 차례로 쓰기 가능해짐
string input = "123 456 789";
stringstream ss(input); // 스트림객체로 변환
int a, b, c;
ss >> a >> b >> c; // int형으로 바로 받을 수 있음ㅇㅇ
cout << a+b+c << endl; // 1368
getline(ss, item, delimiter): ss를 delimiter로 끊어 담은 item이 존재하는지 확인(true or false 리턴)