-
728x90
[ 풀이 방법 ]
- BFS를 연습하기에 좋은 문제였던 것 같다.
- maps의 방문여부를 저장할 isVisited를 만들고,
방문하지 않은 좌표이면서, maps[r][c]의 값이 1인 곳으로 나아가면서 칸의 수(answer)를 세면 된다.- (0, 0)에서 사방으로 나아가면서 만약 (n, m)에 도달하면 true를 리턴하고,
사방으로 들릴 수 있는 모든 점을 다 들렸지만 (n, m)에는 가지 못 했다면 false를 리턴한다.- bfs결과가 true면 (n, m)까지의 칸의 수인 answer을 리턴하고,
false면 -1을 리턴한다.[ 전체 코드 ]
import java.util.LinkedList;import java.util.Queue;class Solution {static int answer, R, C;static int[] dr = { -1, 1, 0, 0 }, dc = { 0, 0, -1, 1 };static boolean[][] isVisited;public int solution(int[][] maps) {R = maps.length;C = maps[0].length;isVisited = new boolean[R][C];return bfs(maps) ? answer : -1;}private static boolean bfs(int[][] maps) {Queue<int[]> queue = new LinkedList<int[]>();queue.offer(new int[] { 0, 0 });isVisited[0][0] = true;while (!queue.isEmpty()) {int size = queue.size();answer++;while (--size >= 0) {int[] q = queue.poll();if (q[0] == R - 1 && q[1] == C - 1)return true;for (int i = 0; i < 4; i++) {int nr = q[0] + dr[i];int nc = q[1] + dc[i];if (nr < 0 || nc < 0 || nr >= R || nc >= C || isVisited[nr][nc] || maps[nr][nc] == 0)continue;isVisited[nr][nc] = true;queue.offer(new int[] { nr, nc });}}}return false;}}데롱디롱희희.. (๑′ᴗ‵๑)
'알고리즘 풀이 > 프로그래머스' 카테고리의 다른 글
[level1] 프로그래머스 - 없는 숫자 더하기(JAVA) (0) 2021.10.10 [level1] 프로그래머스 - 최소직사각형(JAVA) (0) 2021.10.10 [level2] 프로그래머스 - 가장 큰 수(JAVA) (0) 2021.09.20 [level2] 프로그래머스 - 빛의 경로 사이클(JAVA) (2) 2021.09.20 [level2] 프로그래머스 - 행렬 테두리 회전하기(JAVA) (0) 2021.09.19