☑️ 문제: 리코쳇 로봇
https://school.programmers.co.kr/learn/courses/30/lessons/169199
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
☑️ Code
import java.util.*;
class Solution {
public int solution(String[] board) {
int rowLen = board.length;
int colLen = board[0].length();
// 1. search start Index
int startRow = 0, startCol = 0;
for (int i = 0; i < rowLen; i++) {
for (int j = 0; j < colLen; j++) {
if (board[i].charAt(j) == 'R') {
startRow = i;
startCol = j;
}
}
}
// 2. start에서 시작하기
int answer = bfs(board, startRow, startCol, rowLen, colLen);
return answer;
}
public int bfs(String[] board, int row, int col, int rowLen, int colLen) {
int[] dr = { 0, 0, -1, 1 };
int[] dc = { -1, 1, 0, 0 };
int[][] dist = new int[rowLen][colLen];
for (int i = 0; i < rowLen; i++) {
for (int j = 0; j < colLen; j++) {
dist[i][j] = rowLen * colLen + 1;
}
}
Queue<Integer> queueR = new LinkedList<>();
Queue<Integer> queueC = new LinkedList<>();
dist[row][col] = 0;
queueR.offer(row);
queueC.offer(col);
while (!queueR.isEmpty()) {
row = queueR.poll();
col = queueC.poll();
if (board[row].charAt(col) == 'G') {
return dist[row][col];
}
for (int i = 0; i < 4; i++) {
int nRow = row;
int nCol = col;
while(isBound(nRow, nCol, rowLen, colLen) && board[nRow].charAt(nCol) != 'D') {
nRow += dr[i];
nCol += dc[i];
}
nRow -= dr[i];
nCol -= dc[i];
if (dist[nRow][nCol] > dist[row][col] + 1) {
dist[nRow][nCol] = dist[row][col] + 1;
queueR.offer(nRow);
queueC.offer(nCol);
}
}
}
return -1;
}
boolean isBound(int r, int c, int rLen, int cLen) {
return r >= 0 && c >= 0 && r < rLen && c < cLen;
}
}
'TIL (Today I Learned)' 카테고리의 다른 글
99클럽 코테 스터디 35일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.25 |
---|---|
99클럽 코테 스터디 34일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.24 |
99클럽 코테 스터디 32일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.23 |
99클럽 코테 스터디 31일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.21 |
99클럽 코테 스터디 30일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.21 |