1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { public: int knightDialer(int N) { vector<vector<long>> mtx = { {0, 0, 0, 0, 1, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 0, 1, 0, 0, 0, 1, 0}, {1, 0, 0, 1, 0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 1, 0, 0, 0, 0, 0} }; mtx = pow(mtx, N - 1); vector<vector<long>> f{vector<long>(10, 1)}; f = mul(f, mtx); int res = 0; for (int i = 0; i < 10; ++i) { res = (res + f[0][i]) % M; } return res; }
vector<vector<long>> pow(vector<vector<long>> &mtx, int N) { int n = mtx.size(); vector<vector<long>> res(n, vector<long>(n)); for (int i = 0; i < n; ++i) { res[i][i] = 1; } while (N > 0) { if (N & 1) { res = mul(res, mtx); } mtx = mul(mtx, mtx); N >>= 1; } return res; }
vector<vector<long>> mul(const vector<vector<long>> &a, const vector<vector<long>> &b) { int m = a.size(), n = b.size(), p = b[0].size(); vector<vector<long>> res(m, vector<long>(p)); for (int i = 0; i < m; ++i) { for (int j = 0; j < p; ++j) { for (int k = 0; k < n; ++k) { res[i][j] = (res[i][j] + a[i][k] * b[k][j]) % M; } } } return res; }
int M = 1e9 + 7; };
|