class Solution {
int[][] dirs = null;
Map<Integer,Integer> freqMap = null;
int max = -1;
public int mostFrequentPrime(int[][] mat) {
int rows = mat.length;
int cols = mat[0].length;
int result = -1;
dirs = new int[][] { {-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}};
freqMap = new HashMap<>();
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
boolean[][] visited = new boolean[rows][cols];
bfs(mat, visited, i,j);
}
}
System.out.println(freqMap);
for(Map.Entry<Integer,Integer> entry : freqMap.entrySet()){
int freq = entry.getValue();
int prime = entry.getKey();
if(freq == max){
result = Math.max(result, prime);
}
}
return result;
}
public void bfs( int[][] mat, boolean[][] visited, int r, int c){
int rows = mat.length;
int cols = mat[0].length;
for(int[] dir : dirs){
int row = r;
int col = c;
int total = 0;
while(row >= 0 && col >= 0 && row < rows && col < cols){
int num = mat[row][col];
total = total*10 + num;
if(total > 10 && isPrime(total)){
freqMap.put(total,freqMap.getOrDefault(total,0)+1);
max = Math.max(max, freqMap.get(total));
}
row += dir[0];
col += dir[1];
}
}
}
public boolean isPrime(int number) {
if (number <= 1) {
return false;
}
if (number <= 3) {
return true;
}
if (number % 2 == 0 || number % 3 == 0) {
return false;
}
for (int i = 5; i * i <= number; i = i + 6) {
if (number % i == 0 || number % (i + 2) == 0) {
return false;
}
}
return true;
}
}