본문 바로가기
Beakjoon&프로그래머스/Java

[프로그래머스/Java] 무인도 여행

by 현장 2026. 1. 4.

-Code

import java.util.*;

class Solution {
    static class Position {
        int row, col;
        
        public Position(int row, int col) {
            this.row = row;
            this.col = col;
        }
    }
    
    static boolean[][] visited;
    static int rowSize;
    static int colSize;
    
    public int[] solution(String[] maps) {
        ArrayList<Integer> answer = new ArrayList<>();
        // 범위 구하기
        rowSize = maps.length;
        colSize = maps[0].length();
        // visited 셋팅
        visited = new boolean[rowSize][colSize];
        // 2중 배열로 변경
        for (int row = 0; row < rowSize; row++) {
            for (int col = 0; col < colSize; col++) {
                char now = maps[row].charAt(col);
                // 바다가 아닌 경우 bfs로 계산
                if (!visited[row][col] && now != 'X') {
                    answer.add(bfs(maps, row, col));
                }
            }
        }
        // 비어있는지 확인
        if (answer.size() == 0) {
            answer.add(-1);
        } else {
            answer.sort(Comparator.naturalOrder());
        }
        // 반환
        return answer.stream().mapToInt(Integer::intValue).toArray();
    }
    
    private static int bfs(String[] maps, int row, int col) {
        int nowSum = maps[row].charAt(col) - '0';
        // 이동 방향 셋팅
        int[] dRow = {-1, 1, 0, 0};
        int[] dCol = {0, 0, -1, 1};
        // visited와 덱셋팅
        visited[row][col] = true;
        Position start = new Position(row, col);
        Deque<Position> posDeque = new ArrayDeque<>();
        posDeque.addLast(start);
        // 탐색
        while(!posDeque.isEmpty()) {
            Position nowPos = posDeque.pollFirst();
            boolean flag = true;
            
            for (int i = 0; i < 4; i++) {
                int nextRow = nowPos.row + dRow[i];
                int nextCol = nowPos.col + dCol[i];
                // 범위 확인
                if (!canMove(nextRow, nextCol)) continue;
                // 바다인지와 미방문인지 확인
                if(!visited[nextRow][nextCol] && maps[nextRow].charAt(nextCol) != 'X') {
                    visited[nextRow][nextCol] = true;
                    nowSum += maps[nextRow].charAt(nextCol) - '0';
                    posDeque.addLast(new Position(nextRow, nextCol));
                }
            }
        }
        return nowSum;
    }
    
    private static boolean canMove(int row, int col) {
        return (0 <= row && row < rowSize) && (0 <= col && col < colSize);
    }
}

ide를 안쓰고 해보니까 중간중간 코드가 하나씩 빠진거나 셍각을 짧게한 부분 때문에 필요없는 코드도 좀 넣어서 문제가 생겼었습니다. 그래서 해당 부분들을 고치고 해결했습니다.