HJW's IT Blog

[프로그래머스 / C++/ Java / Javascript] 리코쳇 로봇 본문

Algorithm

[프로그래머스 / C++/ Java / Javascript] 리코쳇 로봇

kiki1875 2024. 8. 27. 15:35

문제 설명

리코쳇 로봇이라는 보드게임이 있습니다.

이 보드게임은 격자모양 게임판 위에서 말을 움직이는 게임으로, 시작 위치에서 목표 위치까지 최소 몇 번만에 도달할 수 있는지 말하는 게임입니다.

이 게임에서 말의 움직임은 상, 하, 좌, 우 4방향 중 하나를 선택해서 게임판 위의 장애물이나 맨 끝에 부딪힐 때까지 미끄러져 이동하는 것을 한 번의 이동으로 칩니다.

다음은 보드게임판을 나타낸 예시입니다.

...D..R .D.G... ....D.D D....D. ..D....

여기서 "."은 빈 공간을, "R"은 로봇의 처음 위치를, "D"는 장애물의 위치를, "G"는 목표지점을 나타냅니다.

위 예시에서는 "R" 위치에서 아래, 왼쪽, 위, 왼쪽, 아래, 오른쪽, 위 순서로 움직이면 7번 만에 "G" 위치에 멈춰 설 수 있으며, 이것이 최소 움직임 중 하나입니다.

게임판의 상태를 나타내는 문자열 배열 board가 주어졌을 때, 말이 목표위치에 도달하는데 최소 몇 번 이동해야 하는지 return 하는 solution함수를 완성하세요. 만약 목표위치에 도달할 수 없다면 -1을 return 해주세요.

입출력 예

board result

["...D..R", ".D.G...", "....D.D", "D....D.", "..D...."] 7
[".D.R", "....", ".G..", "...D"] -1

코드

#include <bits/stdc++.h>
using namespace std;

pair<int,int> start;
pair<int,int> goal;

int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};

int bfs(vector<string>& board){
    int n = board.size();
    int m = board[0].length();
    vector<vector<bool>> visited(n, vector<bool>(m, false));
    
    queue<pair<pair<int,int>,int>> q;

    q.push({start, 0});
    visited[start.first][start.second] = true;

    while(!q.empty()){
        auto [pos, cnt] = q.front();
        int x = pos.first; int y = pos.second;

        q.pop();
        if(x == goal.first && y == goal.second){
            return cnt;
        }

        for(int i = 0; i<4; i++){
            int nx = x; int ny = y;

            while(true){
                int next_x = nx + dx[i];
                int next_y = ny + dy[i];
                if(next_x < 0 || next_y < 0 || next_x >= board.size() || next_y >= board[0].length() || board[next_x][next_y] == 'D') break;
                nx = next_x; ny = next_y;
            }

            if(!visited[nx][ny]){
                visited[nx][ny] = true;
                q.push({{nx,ny}, cnt+1});
            }
        }

    }
    return -1;
}

int solution(vector<string> board) {
    int answer = -1;

    for(int i = 0; i<board.size(); i++){
        for(int j = 0; j<board[0].length(); j++){
            if(board[i][j] == 'R') start = {i,j};
            if(board[i][j] == 'G') goal = {i,j};
        }
    }
    answer = bfs(board);

    return answer;
}

 

JAVA

 

 

import java.sql.Struct;
import java.util.LinkedList;
import java.util.Queue;
class Triple{
    int x;
    int y;
    int cost;

    public Triple(int x, int y , int cost){
        this.x = x;
        this.y = y;
        this.cost = cost;
    }
}
class Solution {

    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0,0,-1,1};
    int width, height;
    int[] start, goal;
    boolean[][] visited;

    public boolean isValid(int x, int y, String[] board){
        if(x < 0 || y < 0 || x >= height || y >= width) return false;
        if(board[x].charAt(y) == 'D') return false;
        return true;
    }
    public int bfs(String[] board){

        Queue<Triple> q = new LinkedList<>();
        q.add(new Triple(start[0], start[1], 0));
        visited[start[0]][start[1]] = true;

        while(!q.isEmpty()){
            Triple top = q.poll();
            int x = top.x;
            int y = top.y;
            int cost = top.cost;

            if(x == goal[0] && y == goal[1]){
                return cost;
            }

            for(int i = 0; i<4; i++){
                int nx = x + dx[i];
                int ny = y + dy[i];

                if(!isValid(nx, ny, board)) continue;

                while(true){
                    nx += dx[i];
                    ny += dy[i];

                    if(!isValid(nx, ny, board)) {
                        nx -= dx[i];
                        ny -= dy[i];
                        break;
                    }
                }

                if(visited[nx][ny]) continue;
                visited[nx][ny] = true;
                q.add(new Triple(nx, ny, cost + 1));
            }
        }


        return -1;
    }
    public int solution(String[] board) {
        int answer = 0;
        height = board.length;
        width = board[0].length();

        visited = new boolean[height][width];

        for(int i = 0; i<height; i++){
            for(int j = 0; j<width; j++){
                if(board[i].charAt(j) == 'R'){
                    start = new int[]{i,j};
                }
                else if(board[i].charAt(j) == 'G'){
                    goal = new int[]{i,j};
                }
            }
        }

        return bfs(board);
    }

}

 

Javascript

 


/*
  한번 움직이기 시작하면 장애물이나 가장자리에 도달할때까지 움직인다
*/

function solution(board) {
  var answer = 0;

  const height = board.length;
  const width = board[0].length;
  const dx = [-1,1,0,0];
  const dy = [0,0,-1,1];
  const visited = Array(height).fill().map(()=> Array(width).fill(false));
  let start = [];
  let goal = [];

  for(let i = 0; i<height; i++){
    for(let j = 0; j<width; j++){
      if(board[i][j] === "R") start = [i,j];
      else if (board[i][j] === "G") goal = [i,j];
    }
  }

  function bfs(){
    let q = [];
    q.push([...start, 0]);
    visited[start[0]][start[1]] = true;

    while(q.length){
      let [curX, curY, cost] = q.shift();

      if(curX === goal[0] && curY === goal[1]){
        return cost;
      }

      for(let i = 0; i<4; i++){
        let nx = curX + dx[i];
        let ny = curY + dy[i];
        let nCost = cost + 1;

        if(!isValid(nx,ny)) continue;

        while(true){
          nx += dx[i];
          ny += dy[i];

          if(!isValid(nx, ny)){
            nx -= dx[i];
            ny -= dy[i];
            break;
          }
          if(board[nx][ny] === "D"){
            nx -= dx[i];
            ny -= dy[i];
            break;
          }
        }

        if(visited[nx][ny]) continue;

        visited[nx][ny] = true;
        q.push([nx, ny, nCost]);

      }
    }
    return -1;
  }

  function isValid(x, y){
    if(x < 0 || y < 0 || x >= height || y >= width ) return false;
    if(board[x][y] === "D") return false;

    return true;
  }




  return bfs();
}


console.log(solution([".D.R", "....", ".G..", "...D"]))