TIL (Today I Learned)

99클럽 코테 스터디 35일차 TIL + 오늘의 학습 키워드

남 희 2024. 8. 25. 22:20

☑️ 문제: 게임 맵 최단거리

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

☑️ Code: BFS 풀이

import java.util.*;

class Solution {
    public int solution(int[][] maps) {                
        // 0. init data  
        int n = maps.length;
        int m = maps[0].length; 
        Queue<Integer> queue = new LinkedList<>();
        int[][] dist = new int[n][m];

        // 1. push first point
        int x = 0, y = 0;
        queue.offer(x);
        queue.offer(y);
        dist[y][x] = 1;
        
        // 2. bfs
        int answer = -1;
        int nx, ny;
        int[] dx = { 0, 0, 1, -1 };
        int[] dy = { 1, -1, 0, 0 };
        while (!queue.isEmpty()) {
            x = queue.poll();
            y = queue.poll();
            if (x == m - 1 && y == n - 1) {
                answer = dist[y][x];
                break;
            }
            
            for (int i = 0; i < 4; i++) {
                nx = x + dx[i];
                ny = y + dy[i];
                if (!isOutBound(nx, ny, n, m) && maps[ny][nx] == 1 && dist[ny][nx] == 0) {
                    queue.offer(nx);
                    queue.offer(ny);
                    dist[ny][nx] = dist[y][x] + 1;
                }
            }
        }
        
        return answer;
    }
    
    boolean isOutBound(int x, int y, int n, int m) {
        return y < 0 || y >= n || x < 0 || x >= m;
    }
}