anott
기록
anott
  • 분류 전체보기
    • 오라클
    • SQL
    • 알고리즘
      • 백준저지
      • 프로그래머스
      • SWEA
    • 개발 관련
    • 프론트엔드
      • TypeScript, Next.js
      • React 공식문서 읽기
hELLO · Designed By 정상우.
anott

기록

프로그래머스 게임 맵 최단거리 (Java)
알고리즘/프로그래머스

프로그래머스 게임 맵 최단거리 (Java)

2021. 10. 5. 01:05

출처: https://programmers.co.kr/learn/courses/30/lessons/1844

 

코딩테스트 연습 - 게임 맵 최단거리

[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1

programmers.co.kr

 

접근 방법

전형적인 bfs 문제라고 생각한다.

 

 

 

생각

급한 마음에 문제를 대충 읽고 가로 세로가 5로 고정되어 있고, 또 0인 곳을 이동한다고 착각했다. 차근차근 문제를 읽어야겠다.

 

 

 

코드

import java.util.*;

class Solution {

    static private class Position {
        int x, y, cnt;

        public Position(int x, int y, int cnt) {
            this.x = x;
            this.y = y;
            this.cnt = cnt;
        }
    }

    public int solution(int[][] maps) {
        int answer = -1; // 초기화

        int mapLenX = maps.length;
        int mapLenY = maps[0].length;
        int[][] d = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };
        boolean[][] visited = new boolean[mapLenX][mapLenY];
        Queue<Position> q = new LinkedList<>();

        q.add(new Position(0, 0, 1)); // 시작
        visited[0][0] = true;

        while (!q.isEmpty()) { // bfs
            Position cur = q.poll();

            if (cur.x == mapLenX - 1 && cur.y == mapLenY - 1) { // 종료조건
                answer = cur.cnt;
                break;
            }

            for (int i = 0; i < 4; i++) {
                int dx = cur.x + d[i][0];
                int dy = cur.y + d[i][1];

                if (dx >= 0 && dx < mapLenX && dy >= 0 && dy < mapLenY && 
                	!visited[dx][dy] && maps[dx][dy] == 1) {
                    visited[dx][dy] = true;
                    q.add(new Position(dx, dy, cur.cnt + 1));
                }
            }
        }

        return answer;
    }
}

 

저작자표시 비영리

'알고리즘 > 프로그래머스' 카테고리의 다른 글

프로그래머스 정수 삼각형  (0) 2021.09.22
프로그래머스 뉴스 클러스터링  (0) 2021.09.21
프로그래머스 메뉴 리뉴얼  (0) 2021.09.13
프로그래머스 순위 검색  (0) 2021.09.09
프로그래머스 구명보트  (0) 2021.09.07
    '알고리즘/프로그래머스' 카테고리의 다른 글
    • 프로그래머스 정수 삼각형
    • 프로그래머스 뉴스 클러스터링
    • 프로그래머스 메뉴 리뉴얼
    • 프로그래머스 순위 검색
    anott
    anott

    티스토리툴바