[BOJ 1103] ๊ฒŒ์ž„

 

1. ๋ฌธ์ œ : https://www.acmicpc.net/problem/1103

 

2. ํ’€์ด

dfs + dp ๋ฌธ์ œ

 

3. ์ฝ”๋“œ

package baekjoon;

import java.util.*;

public class Main {
    static int N, M;
    static int[][] map;
    static boolean[][] visit;
    static int[][] dp;
    static int[] dx = {-1, 1, 0, 0}, dy = {0, 0, -1, 1};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        map = new int[N][M];
        visit = new boolean[N][M];
        dp = new int[N][M];

        for (int[] arr : dp) Arrays.fill(arr, -1);

        for (int i = 0; i < N; i++) {
            String s = sc.next();
            for (int j = 0; j < s.length(); j++) {
                char c = s.charAt(j);
                map[i][j] = c - '0' <= 9 ? c - '0' : 0;
            }
        }

        System.out.println(dfs(0, 0));
    }

    static int dfs(int x, int y) {
        if (!inRange(x, y) || map[x][y] == 0) return 0;
        if (visit[x][y]) {
            System.out.println(-1);
            System.exit(0);
        }
        if (dp[x][y] != -1) return dp[x][y];

        visit[x][y] = true;

        for (int d = 0; d < 4; d++) {
            int nx = x + dx[d] * map[x][y], ny = y + dy[d] * map[x][y];
            dp[x][y] = Math.max(dp[x][y], dfs(nx, ny) + 1);
        }

        visit[x][y] = false;

        return dp[x][y];
    }

    static boolean inRange(int x, int y) {
        if (x < 0 || x > N - 1 || y < 0 || y > M - 1) return false;
        return true;
    }
}

'๐Ÿ’ป Coding Problems Solving > Dynamic Programming' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode] Subarray Sum Equals K  (0) 2023.07.23
[BOJ 1890] ์ ํ”„ (java)  (0) 2023.04.20
[LeetCode] Longest Increasing Subsequence  (0) 2023.03.30
[LeetCode] Coin Change  (0) 2023.03.29
[LeetCode] Maximum Product Subarray  (0) 2023.03.28
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ