[백준] 2178 미로 탐색

leeng·2023년 7월 31일
0
    public static void main(String[] args) {
        int n = 7;
        int m = 7;

        String[] strs = new String[n];
//        strs[0] = "101111";
//        strs[1] = "101010";
//        strs[2] = "101011";
//        strs[3] = "111011";
        strs[0] = "1011111";
        strs[1] = "1110001";
        strs[2] = "1000001";
        strs[3] = "1000001";
        strs[4] = "1000001";
        strs[5] = "1000001";
        strs[6] = "1111111";
		search(n, m, strs)
    }

    static int search(int n, int m, String[] strs) {
        int result;
        int[][] arr = new int[n+1][m+1];
        boolean[][] visited = new boolean[n+1][m+1];

        for (int i = 1; i < n + 1; i++) {
            String[] line = strs[i-1].split("");
            for (int j = 1; j < m + 1; j++) {
                arr[i][j] = Integer.parseInt(line[j-1]);
            }
        }

        int row = 1;
        int col = 1;

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[] {row, col});
        visited[row][col] = true;

        while (queue.size() > 0) {
            int[] rowAndCol = queue.poll();
            int _row = rowAndCol[0];
            int _col = rowAndCol[1];

            for (int i = _row - 1; i <= _row + 1; i++) { // _col은 고정
                if (i > 0 && i < n +1) {
                    if (!visited[i][_col] && arr[i][_col] == 1) {
                        arr[i][_col] = arr[_row][_col] + 1;
                        queue.offer(new int[]{i, _col});
                        visited[i][_col] = true;
                    }
                }
            }

            for (int i = _col - 1; i <= _col + 1; i++) { // _row은 고정
                if (i > 0 && i < m + 1) {
                    if (!visited[_row][i] && arr[_row][i] == 1) {
                        arr[_row][i] = arr[_row][_col] + 1;
                        queue.offer(new int[]{_row, i});
                        visited[_row][i] = true;
                    }
                }
            }
        }

        result = arr[n][m];
        
        return result;
    }
profile
기술블로그보다는 기록블로그

0개의 댓글