935. Knight Dialer
static const int MOD = 1000000007;
// Dynamic Programming
int knightDialer(int N) { // time: O(N); space: O(1)
vector<vector<int> > neighbors({ {4,6}, {6,8}, {7,9}, {4,8}, {0,3,9}, {}, {0,1,7}, {2,6}, {1,3}, {2,4} });
vector<long> count(10, 1);
for (int i = 0; i < N - 1; ++i) {
vector<long> tmp(10, 0);
for (int j = 0; j < 10; ++j) { // position
for (int k : neighbors[j]) { // neighbor
tmp[j] = (tmp[j] + count[k]) % MOD;
}
}
count = tmp;
}
return accumulate(count.begin(), count.end(), (long)0) % MOD;
}Last updated

