프로그래머스 169199 리코쳇 로봇

1 개요[ | ]

프로그래머스 169199 리코쳇 로봇

2 C++[ | ]

#include <string>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const int MAX = 100;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int visited[MAX][MAX][4];

int solution(vector<string> board) {
    int n = board.size();
    int m = board[0].size();
    queue<pair<pair<int, int>, int>> q;

    // 로봇(R) 위치 찾기
    int rx, ry;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (board[i][j] == 'R') {
                rx = i;
                ry = j;
                break;
            }
        }
    }

    // 초기 방문 설정
    q.push({{rx, ry}, 0});
    for (int i = 0; i < 4; ++i) {
        visited[rx][ry][i] = true;
    }

    while (!q.empty()) {
        int x = q.front().first.first;
        int y = q.front().first.second;
        int moves = q.front().second;
        q.pop();

        if (board[x][y] == 'G') {
            return moves;
        }
        // 모든 방향으로 이동
        for (int i = 0; i < 4; ++i) {
            int nx = x, ny = y;
            // 장애물이나 벽에 부딪힐 때까지 이동
            while (true) {
                nx += dx[i];
                ny += dy[i];
                // 범위를 벗어나거나 장애물을 만나면 중지
                if (nx < 0 || nx >= n || ny < 0 || ny >= m || board[nx][ny] == 'D') {
                    nx -= dx[i];
                    ny -= dy[i];
                    break;
                }
            }
            // 방문하지 않은 위치라면 큐에 추가
            if (!visited[nx][ny][i]) {
                visited[nx][ny][i] = true;
                q.push({{nx, ny}, moves + 1});
            }
        }
    }
    return -1; // 목표에 도달할 수 없는 경우
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}