ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [프로그래머스] 안전지대
    알고리즘 2023. 8. 15. 16:05

    문제

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

    image

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

    풀이

    간단히 생각해서 모든 맵을 탐색해야 한다고 생각하였다.
    따라서 지뢰의 좌표 -> 주변 탐색 방식으로 풀이하였다.
    이때 주의할 점은 인접한 지역에 지뢰가 있을 경우 위험지역이 겹치므로 탐색시 visited처리를 해서 탐색하도록 한다.

    import java.util.*;
    import java.lang.*;
    
    class Solution {
        static int[] x_loc = {-1, 0, 1, -1, 1, -1, 0, 1};
        static int[] y_loc = {-1, -1, -1, 0, 0, 1, 1, 1};
        static int count = 0;
    
        public int solution(int[][] board) {
            boolean[][] visited = new boolean[board.length][board[0].length];
            for(int i = 0; i < board.length; i++) {
                for(int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == 1) {
                        count++;
                        bfs(board, visited, i, j);
                    }
                }
            }
    
    
            return board.length * board.length - count;
        }
    
        static void bfs(int[][] map, boolean[][] visited, int startX, int startY) {
            visited[startX][startY] = true;
            for(int i = 0; i < 8; i++) {
                int x = startX + x_loc[i];
                int y = startY + y_loc[i];
    
                if (check(x, y, map) && !visited[x][y]) {
                    visited[x][y] = true;
                    count++;
                }
            }
        }
    
        static boolean check(int x, int y, int[][] map) {
            return x >= 0 && x < map.length && y >= 0 && y < map[0].length && map[x][y] != 1;  
        }
    
        static class Location {
            private int x;
            private int y;
    
            public Location(int x, int y) {
                this.x = x;
                this.y = y;
            }
        }
    }

    https://github.com/Win-9/Algorism/tree/main/programers/%EC%95%88%EC%A0%84%EC%A7%80%EB%8C%80

    728x90

    댓글

Designed by Tistory.