|
| 1 | +import math |
| 2 | + |
| 3 | +class Solution: |
| 4 | + |
| 5 | + def _is_prime(self, n): |
| 6 | + if n <= 1: |
| 7 | + return False |
| 8 | + for i in range(2, int(math.sqrt(n)) + 1): |
| 9 | + if n % i == 0: |
| 10 | + return False |
| 11 | + return True |
| 12 | + |
| 13 | + def mostFrequentPrime(self, M: List[List[int]]) -> int: |
| 14 | + nums = defaultdict(int) |
| 15 | + Y, X = len(M), len(M[0]) |
| 16 | + for y in range(Y): |
| 17 | + for x in range(X): |
| 18 | + for dy, dx in [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]: |
| 19 | + y_, x_ = y, x |
| 20 | + v = M[y][x] |
| 21 | + while Y > y_ + dy >= 0 and X > x_ + dx >= 0: |
| 22 | + y_ += dy |
| 23 | + x_ += dx |
| 24 | + v = v * 10 + M[y_][x_] |
| 25 | + if self._is_prime(v): |
| 26 | + nums[v] += 1 |
| 27 | + |
| 28 | + if not nums: |
| 29 | + return -1 |
| 30 | + |
| 31 | + cnt, res = max(nums.values()), 0 |
| 32 | + for v, c in nums.items(): |
| 33 | + if c == cnt: |
| 34 | + res = max(res, v) |
| 35 | + |
| 36 | + return res |
0 commit comments