


-Code
import java.util.*;
class Solution {
static class Node {
int row;
int col;
int dist;
public Node (int row, int col, int dist) {
this.row = row;
this.col = col;
this.dist = dist;
}
}
static boolean[][] visited;
static int rowSize;
static int colSize;
public int solution(int[][] maps) {
Node startNode = new Node(0, 0, 1);
// row와 col 사이즈 구하기
rowSize = maps.length;
colSize = maps[0].length;
// 방문 여부 확인을 위한 visited 배열 선언
visited = new boolean[rowSize][colSize];
// 최단 거리 구하기
return getShortestDist(startNode, maps);
}
// bfs 로직
private static int getShortestDist(Node startNode, int[][] maps) {
// 이동 방향 셋팅
int[] dRow = {-1, 1, 0, 0};
int[] dCol = {0, 0, -1, 1};
// 시작지점 visited 셋팅
visited[startNode.row][startNode.col] = true;
// 덱에 현재 노드 담기
Deque<Node> nodeDeque = new ArrayDeque<>();
nodeDeque.addLast(startNode);
// 덱이 빌때까지 반복
while(!nodeDeque.isEmpty()) {
// 현재 노드 poll
Node nowNode = nodeDeque.pollFirst();
int nowRow = nowNode.row;
int nowCol = nowNode.col;
// 목적지에 도착하면 거리 반환
if (nowRow == rowSize - 1 && nowCol == colSize - 1) {
return nowNode.dist;
}
// 상하좌우를 돌면서 탐색
for (int i = 0; i < 4; i++) {
int nextRow = nowRow + dRow[i];
int nextCol = nowCol + dCol[i];
// 범위 확인
if (!canMove(nextRow, nextCol, rowSize, colSize)) {
continue;
}
// 방문 여부 확인 및 미방문이면 탐색
if (!visited[nextRow][nextCol] && maps[nextRow][nextCol] == 1) {
visited[nextRow][nextCol] = true;
Node nextNode = new Node(nextRow, nextCol, nowNode.dist + 1);
nodeDeque.addLast(nextNode);
}
}
}
return -1;
}
// 이동 가능한 위치인지 확인
private static boolean canMove(int row, int col, int rowSize, int colSize) {
return (0 <= row && row < rowSize) && (0 <= col && col < colSize);
}
}'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [프로그래머스/Java] 더 맵게 (0) | 2026.01.04 |
|---|---|
| [프로그래머스/Java] 무인도 여행 (0) | 2026.01.04 |
| [백준/Java] 24052번 알고리즘 수업 - 삽입 정렬 2 (0) | 2026.01.04 |
| [백준/Java] 5430번 AC (0) | 2026.01.04 |
| [백준/Java] 16928번 뱀과 사다리 게임 (0) | 2026.01.03 |