프로그래머스 [JAVA] :: 안전지대

smi·2023년 1월 22일
0

📚 문제 정의

다음 그림과 같이 지뢰가 있는 지역과 지뢰에 인접한 위, 아래, 좌, 우 대각선 칸을 모두 위험지역으로 분류합니다.

지뢰는 2차원 배열 board에 1로 표시되어 있고 board에는 지뢰가 매설 된 지역 1과, 지뢰가 없는 지역 0만 존재합니다.
지뢰가 매설된 지역의 지도 board가 매개변수로 주어질 때, 안전한 지역의 칸 수를 return하도록 solution 함수를 완성해주세요.


📝 제한사항

  • board는 n * n 배열입니다.
  • 1 ≤ n ≤ 100
  • 지뢰는 1로 표시되어 있습니다.
  • board에는 지뢰가 있는 지역 1과 지뢰가 없는 지역 0만 존재합니다.

📝 입출력 예

boardresult
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]16
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0]]13
[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]0

💡 참고코드

class Solution {
    public int solution(int[][] board) {
        int answer = 0;
        boolean landmine[][] = new boolean[board.length][board.length];
        
        for(int row = 0; row < landmine.length; row++) {
            for(int col = 0; col < landmine.length; col++) {
                if(board[row][col] == 1) Destroy(col, row, board.length, landmine);
            }
        }
        
        for(int i = 0; i < landmine.length; i++) {
            for(int j = 0; j < landmine.length; j++) {
                if(landmine[i][j] == false) answer++;
            }
        }
        
        return answer;
    }
    
    private static void Destroy(int col, int row, int n, boolean[][] landmine) {
        for(int r = row-1; r < row+2; r++) {
            if(r < 0 || r >= n) continue;
            else {
                for(int c = col-1; c < col+2; c++) {
                    if(c < 0 || c >= n) continue;
                    else landmine[r][c] = true;
                }
            }
        }
    }
    
}

memo.

❗️함수 자주 사용하기

profile
공부한 거 올려요 :)

0개의 댓글