forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d21b007
commit 6fe2ab7
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
#include <iostream> | ||
#include <vector> | ||
#include <numeric> | ||
using namespace std; | ||
|
||
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }(); | ||
class Solution | ||
{ | ||
public: | ||
int knightDialer(int N) | ||
{ | ||
vector<long long> result(10, 1); | ||
vector<long long> mem(10); | ||
long long mod = 1e9+7; | ||
for (int i = 1; i < N; i++) | ||
{ | ||
mem[0] = (result[4] + result[6]) % mod; | ||
mem[1] = (result[6] + result[8]) % mod; | ||
mem[2] = (result[7] + result[9]) % mod; | ||
mem[3] = (result[4] + result[8]) % mod; | ||
mem[4] = (result[0] + result[3] + result[9]) % mod; | ||
mem[5] = 0; | ||
mem[6] = (result[0] + result[1] + result[7]) % mod; | ||
mem[7] = (result[6] + result[2]) % mod; | ||
mem[8] = (result[1] + result[3]) % mod; | ||
mem[9] = (result[2] + result[4]) % mod; | ||
result = mem; | ||
} | ||
return accumulate(result.begin(), result.end(), 0, | ||
[=](long long s, long long n) { return int((s + n) % mod);}); | ||
} | ||
}; | ||
int main() | ||
{ | ||
int N = 2; | ||
cout << Solution().knightDialer(N); | ||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
from ctypes import c_uint32 | ||
class Solution: | ||
hops = [(c_uint32 * 4)(4, 2, 2, 1)] | ||
def knightDialer(self, N): | ||
""" | ||
:type N: int | ||
:rtype: int | ||
""" | ||
if N == 1: | ||
return 10 | ||
|
||
mod = 10**9 + 7 | ||
|
||
if N <= len(self.hops): | ||
H = self.hops[N - 1] | ||
else: | ||
H = self.hops[-1] | ||
for _ in range(len(self.hops), N): | ||
H = (c_uint32 * 4)(2*(H[1] + H[2]), 2*H[3] + H[0], H[0], H[1]) | ||
for i in (0, 1, 2, 3): | ||
H[i] %= mod | ||
self.hops.append(H) | ||
|
||
return sum(H) % mod | ||
|
||
if __name__ == "__main__": | ||
N = 2 | ||
print(Solution().knightDialer(N)) |