프로그래머스 리코쳇 로봇 C++

2023. 9. 17. 19:16알고리즘

#include <string>
#include <vector>
#include <queue>
#include <iostream>

using namespace std;

int visited[101][101];
int stx, sty;
int row_length, col_length;
int dx[4]= {-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};

int bfs(vector<string> board){
    queue<pair<int, int>> q;
    visited[sty][stx]=0;
    q.push({stx, sty});
    while (!q.empty()){
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        if (board[y][x]=='G'){
            return visited[y][x];
        }
        for (int i=0;i<4;i++){
            int nx = x, ny = y;
            while (nx+dx[i]>=0 &&nx+dx[i]<row_length&& ny+dy[i]>=0 &&ny+dy[i]<col_length&&board[ny+dy[i]][nx+dx[i]]!='D'){
                nx = nx+dx[i];
                ny = ny+dy[i];
            }
            if (visited[ny][nx]==-1){
                visited[ny][nx]=visited[y][x]+1;
                q.push({nx, ny});
            }
        }
        
    }
    return -1;
}

int solution(vector<string> board) {
    int answer = 0;
    col_length = board.size();
    row_length = board[0].size();
    for (int i=0;i<col_length;i++){
        for (int j=0;j<row_length;j++){
            if (board[i][j]=='R'){
                stx = j, sty = i;
            }
        }
    }
    for (int i=0;i<101;i++){
        for (int j=0;j<101;j++){
            visited[i][j]=-1;
        }
    }
    answer = bfs(board);
    return answer;
}

간단한 bfs 문제이다!

 

 

'알고리즘' 카테고리의 다른 글

프로그래머스 연속 부분 수열 합의 개수 C++  (0) 2023.09.18
프로그래머스 모음사전 C++ dfs  (0) 2023.09.17
백준 14503 C++ 로봇청소기  (0) 2023.09.15
백준 14500 테트로미노 c++ (dfs)  (0) 2023.09.01
후...  (0) 2023.08.29