[카카오 인턴] 경주로 건설

2025. 6. 1. 22:23·Algorithm/프로그래머스

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

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

접근 방식

(0,0)부터 (n-1, n-1)까지 도달한다고 할 때, 모든 경우의 수를 고려하는 것을 어떻게 할까? 가 첫번째 관문이였다.

백트래킹을 떠올렸으나, 25 x 25인 경우엔 시간초과가 날 것이기 때문에 제외했다.

 

boolean visited를 사용하여 코드를 짰지만, 당연히 하나의 최단경로만 탐색했다. 문제에서 원하는 것은 모든 경우의 수에서 최소 값이다.

 

따라서, int visited를 통해서 현재 값들을 배열에 저장해두고, 최소 비용이 갱신되는 경우에만 다음 칸으로 탐색이 가능하게 구현했다.

또한, 방향에 따라서 100, 600값이 달라지므로 현재 방향을 저장하는 값을 큐에 넣어서 다음 탐색 방향이 같은 경우 +100, 아닌경우 +600 이런식으로 구현했다. 

 

코드

import java.util.*;
class Solution {
    static int n;
    static int[] dx = {1, 0, -1, 0};
    static int[] dy = {0, 1, 0, -1};
    static int min_cost = Integer.MAX_VALUE;
    public int solution(int[][] board) {
        int answer = 0;
        n = board.length;
        
        bfs(0, board);
        bfs(1, board);
        
        return min_cost;
    }
    
    public void bfs(int direction, int[][] board) {
        Queue<Point> q = new LinkedList<>();
        q.add(new Point(0, 0, direction, 0));
        
        int[][] visited = new int[n][n];
        visited[0][0] = 100;
        
        while(!q.isEmpty()) {
            Point cur = q.poll();
            int x = cur.x;
            int y = cur.y;
            int curDir = cur.dir;
            int cost = cur.cost;
            
            if (x == n - 1 && y == n - 1) {
                //System.out.println(cost);
                min_cost = Math.min(min_cost, cost);
                continue;
            }
            
            for(int dir = 0; dir < 4; dir++) {
                int nx = x + dx[dir];
                int ny = y + dy[dir];
                if (nx < 0 || ny < 0 || nx >= n || ny >= n) continue;
                if (board[nx][ny] == 1) continue;
                
                int nextCost = 0;
                if (curDir == dir) nextCost = cost + 100;
                else nextCost = cost + 600;
                
                if (visited[nx][ny] == 0 || nextCost < visited[nx][ny]) {
                    visited[nx][ny] = nextCost;
                    q.add(new Point(nx, ny, dir, nextCost));
                }
            }
        }
    }
    
    public class Point {
        int x;
        int y;
        int dir;
        int cost;
        public Point(int x, int y, int dir, int cost) {
            this.x = x;
            this.y = y;
            this.dir = dir;
            this.cost = cost;
        }
    }
}

 

후기

bfs만 보면 반사적으로 visited.. 이렇게 생각했는데 최소 cost를 계산하는 경우에는 int 배열을 통해 다음 탐색 지점을 찾도록 하자.

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

프로그래머스 Lv.1 카카오 구현 부시기  (0) 2025.04.06
[프로그래머스] 지게차와 크레인  (0) 2025.02.25
조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기  (1) 2024.12.30
자동차 평균 대여 기간 구하기  (1) 2024.12.29
즐겨찾기가 가장 많은 식당 정보 출력하기  (3) 2024.12.26
'Algorithm/프로그래머스' 카테고리의 다른 글
  • 프로그래머스 Lv.1 카카오 구현 부시기
  • [프로그래머스] 지게차와 크레인
  • 조회수가 가장 많은 중고거래 게시판의 첨부파일 조회하기
  • 자동차 평균 대여 기간 구하기
미네구스
미네구스
  • 미네구스
    망구스 blog
    미네구스
  • 전체
    오늘
    어제
    • 분류 전체보기 (174)
      • Kotlin (0)
      • 시큐리티 (0)
        • 개발자 유미 (0)
      • 배포 (4)
      • 회고 (0)
      • Algorithm (142)
        • 프로그래머스 코딩테스트 문제풀이전략 (37)
        • 백준 (65)
        • 프로그래머스 (18)
        • Leetcode (22)
        • 코테 팁 (0)
      • 프로젝트 (8)
        • WEPIK (3)
        • PICK-O (5)
      • CS (1)
        • 운영체제 (5)
        • 네트워크 (1)
        • 면접스터디 (2)
      • 면접 (1)
        • 코테후기 (0)
        • 면접후기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백트래킹
    `
    N과 M
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
미네구스
[카카오 인턴] 경주로 건설
상단으로

티스토리툴바