935. Knight Dialer

  • μ „ν™” 닀이얼 μœ„μ—μ„œ 체슀의 λ‚˜μ΄νŠΈ 말을 μ›€μ§μ—¬μ„œ λ§Œλ“€ 수 μžˆλŠ” 번호의 경우의 수λ₯Ό κ΅¬ν•˜λŠ” 문제.
  • 닀이얼 μœ„μ—μ„œ 말을 움직여 보면 μ•„λž˜μ™€ 같이 λ‹€μŒ μˆ«μžλ“€μ΄ μ •ν•΄μ§€λŠ” 것을 μ•Œ 수 μžˆλ‹€.
1 β†’ 6, 8 / 2 β†’ 7, 9 / 3 β†’ 4, 8 / 4 β†’ 3, 9, 0 / 5 β†’ μ—†μŒ / 6 β†’ 1, 7, 0 / 7 β†’ 2, 6 / 8 β†’ 1, 3 / 9 β†’ 2, 4 / 0 β†’ 4, 6
  • 첫번째 μˆ«μžλΆ€ν„° μ‹œμž‘ν•˜μ—¬ λ‹€μŒ 숫자둜 κ°€λŠ₯ν•œ 경우의 수λ₯Ό νƒμƒ‰ν•΄λ‚˜κ°„λ‹€.
    • 이 λ•Œ 계산해 λ‘” 경우의 수λ₯Ό matrix dp 에 기둝해둔닀.
    • 번호의 μ΅œλŒ€ 길이가 5000, 각 길이 λ§ˆλ‹€ μžλ¦¬μˆ˜λŠ” 10κ°œμ΄λ―€λ‘œ 총 50000 개λ₯Ό 기둝할 수 μžˆλŠ” 곡간이 ν•„μš”ν•˜λ‹€.
    • μ–΄μ°¨ν”Ό 각 ν…ŒμŠ€νŠΈ μΌ€μ΄μŠ€ λ§ˆλ‹€ μ €μž₯λ˜λŠ” 값이 λ™μΌν•˜κΈ° λ•Œλ¬Έμ— static λ³€μˆ˜λ‘œ λ‘λŠ”κ²Œ μœ λ¦¬ν•˜λ‹€.
class Solution { public: static constexpr int MOD = 1e9 + 7; static map<int, vector<int>> nextDigits; static vector<vector<int>> dp; int dfs(int n, int digit) { if (n == 1) return nextDigits[digit].size(); if (dp[n][digit] != -1) return dp[n][digit]; int result = 0; for (auto nextDigit : nextDigits[digit]) { result = (result + dfs(n - 1, nextDigit)) % MOD; } return dp[n][digit] = result; } int knightDialer(int n) { if (n == 1) return 10; int result = 0; for (int i = 0; i <= 9; ++i) { result = (result + dfs(n - 1, i)) % MOD; } return result; } }; map<int, vector<int>> Solution::nextDigits = { {1, {6, 8}}, {2, {7, 9}}, {3, {4, 8}}, {4, {3, 9, 0}}, {5, {}}, {6, {1, 7, 0}}, {7, {2, 6}}, {8, {1, 3}}, {9, {2, 4}}, {0, {4, 6}}, }; vector<vector<int>> Solution::dp(5000, vector<int>(10, -1));