다음 그림과 같이 지뢰가 있는 지역과 지뢰에 인접한 위, 아래, 좌, 우 대각선 칸을 모두 위험지역으로 분류합니다.
image.png
지뢰는 2차원 배열 board에 1로 표시되어 있고 board에는 지뢰가 매설 된 지역 1과, 지뢰가 없는 지역 0만 존재합니다.
지뢰가 매설된 지역의 지도 board가 매개변수로 주어질 때, 안전한 지역의 칸 수를 return하도록 solution 함수를 완성해주세요.
https://school.programmers.co.kr/learn/courses/30/lessons/120866
class Solution {
public static int solution(int[][] board) {
int[][] boomBoard = new int[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 1) checkExplosion(i, j, boomBoard);
}
}
int count = 0;
for (int[] array : boomBoard) {
for (int value : array) {
if (value == 0) count++;
}
}
return count;
}
static void checkExplosion(int x, int y, int[][] boomBoard) {
int explosionX;
int explosionY;
int[] aroundX = {0, -1, -1, -1, 0, 0, 1, 1, 1};
int[] aroundY = {0, -1, 0, 1, -1, 1, -1, 0, 1};
for (int i = 0; i < 9; i++) {
explosionX = x + aroundX[i];
explosionY = y + aroundY[i];
if (explosionX < boomBoard.length && explosionY < boomBoard.length)
if (explosionX >= 0 && explosionY >= 0) boomBoard[explosionX][explosionY] = 1;
}
}
}
- 반복문을 통해 1있는 곳을 확인한 후, 함수 호출하여 주위 값을 1로 체크한다.
- 0값을 카운트하여 리턴.