본문 바로가기

Coding Test

백준 보드점프(3372)

 

오늘은 DP문제를 풀었다

 

https://www.acmicpc.net/problem/3372

 

3372번: 보드 점프

N × N 게임 보드에 양의 숫자들이 적혀있다. 목적은 왼쪽 위에서 오른쪽 아래까지 규칙에 맞게 점프를 해서 가는 것이다. 숫자들은 현재 점에서 갈 수 있는 거리를 의미한다. 반드시 오른쪽이나

www.acmicpc.net

 

 

문제는 크게 어렵지 않다 처음 시작점부터 점프가능한 부분의 영역을 DP해가면서 진행하면된다.

 

크기가 굉장히 큰편이기에 BigInteger를 사용했다.

 

처음에는 모두 0으로 초기화 안하고 NULL체크로 진행했는데 종착점을 0으로 초기화 하지않으면 통과하지 못하는 케이스가 있어 고전했다.

 

알고리즘은 쉽지만 조건이 약간 귀찮은 문제였다.

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static int[][] dir = {
            {0, 1},
            {1, 0}
    };

    public static void main(String[] args) throws IOException {
        solution();
    }


    public static void solution() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        int[][] map = new int[N][N];
        BigInteger[][] dp = new BigInteger[N][N];

        for (int i=0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int j=0; j < N; j++) {
                map[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        for (int i=0; i < N; i++) Arrays.fill(dp[i], new BigInteger("0"));
        dp[0][0] = new BigInteger("1");

        for (int i=0; i < N; i++) {

            for (int j=0; j < N; j++) {
                if (dp[i][j] == null) continue;
                else if (map[i][j] == 0) continue;

                for (int k=0; k < dir.length; k++) {
                    int x = i + (dir[k][0] *  map[i][j]);
                    int y = j + (dir[k][1] *  map[i][j]);


                    if (x >=0 && y >=0 && x < N && y < N ) {
                        dp[x][y] = dp[x][y].add(dp[i][j]);
                    }
                }
            }
        }

        for (int i=0; i < N; i++) {
            System.out.println(Arrays.toString(dp[i]));
        }

        System.out.println(dp[N-1][N-1]);


    }


}

 

결과

'Coding Test' 카테고리의 다른 글

백준 나이트의 이동(7562)  (1) 2024.03.20
백준 점프왕 쩰리 (Large)(16174)  (0) 2024.03.18
백준 블랙홀과 소행성(29755)  (0) 2024.03.14
백준 국기 색칠하기(30702)  (0) 2024.03.13
백준 삼각 그래프(4883)  (0) 2024.03.12