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

정상민·2023년 9월 15일

문제링크

문제접근

  • bfs로 탐색하는데 벽 or 장애물 만날 때까지 미끄러지면서 이동

코드

import java.util.*;
class Solution {
    static int[] di = {1,-1,0,0};
    static int[] dj = {0,0,1,-1};
    static int N,M;
    static int answer;
    static int iR,jR,iG,jG;
    static boolean[][] visit;
    static String[] map;
    public int solution(String[] board) {
        map = board;
        N = board.length;
        M = board[0].length();
        visit = new boolean[N][M];
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                char now = board[i].charAt(j);
                if(now == 'R'){
                    iR = i;
                    jR = j;
                }
            }
        }
        bfs();
        return answer;
    }
    private static void bfs(){
        Queue<Integer> que = new LinkedList<>();
        que.add(iR);
        que.add(jR);
        visit[iR][jR] = true;
        while(!que.isEmpty()){
            int size = que.size() / 2;
            answer++;
            for(int s=0;s<size;s++){
                int nowi = que.poll();
                int nowj = que.poll();
                for(int d=0;d<4;d++){
                    int nexti = nowi + di[d];
                    int nextj = nowj + dj[d];
                    while(!(nexti>=N || nexti<0 || nextj<0 || nextj>=M || map[nexti].charAt(nextj)=='D')){
                        nexti += di[d];
                        nextj += dj[d];
                    }
                    nexti -= di[d];
                    nextj -= dj[d];
                    if(nexti == nowi && nextj == nowj) continue;
                    if(visit[nexti][nextj]) continue;
                    else if(map[nexti].charAt(nextj) == 'G') return;
                    que.add(nexti);
                    que.add(nextj);
                    visit[nexti][nextj] = true;
                }
            }
        }
        answer = -1;
        return;
    }
}

결과

정리

  • 오류 잡는데 20분 걸림... 실수 줄이려면 천천히 계획 다 세우고 풀자
profile
안녕하세요! 개인 공부를 꾸준히 기록하는 공간입니다.

0개의 댓글