forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
45 lines (44 loc) · 1.34 KB
/
Solution.cpp
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
class Solution {
public:
int mostFrequentPrime(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
unordered_map<int, int> cnt;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
for (int a = -1; a <= 1; ++a) {
for (int b = -1; b <= 1; ++b) {
if (a == 0 && b == 0) {
continue;
}
int x = i + a, y = j + b, v = mat[i][j];
while (x >= 0 && x < m && y >= 0 && y < n) {
v = v * 10 + mat[x][y];
if (isPrime(v)) {
cnt[v]++;
}
x += a;
y += b;
}
}
}
}
}
int ans = -1, mx = 0;
for (auto& [v, x] : cnt) {
if (mx < x || (mx == x && ans < v)) {
mx = x;
ans = v;
}
}
return ans;
}
private:
bool isPrime(int n) {
for (int i = 2; i <= n / i; ++i) {
if (n % i == 0) {
return false;
}
}
return true;
}
};