-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path6th_Jan.java
More file actions
43 lines (40 loc) · 1.25 KB
/
Copy path6th_Jan.java
File metadata and controls
43 lines (40 loc) · 1.25 KB
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
class Solution
{
boolean[] prime = new boolean[10000];
Solution()
{
Arrays.fill(prime,true);
for(int i = 2;i*i<10000;i++){
if(prime[i]==true){
for(int j = i*i;j<10000;j+=i){
prime[j] = false;
}
}
}
}
public int shortestPath(int Num1,int Num2){
// Complete this function using prime array
boolean[]vis=new boolean[10000];
Queue<int[]> q=new LinkedList<>();
q.add(new int[]{Num1,0});
vis[Num1]=true;
while(!q.isEmpty()){
int[] curr=q.remove();
if(curr[0]==Num2)return curr[1];
char[] arr= Integer.toString(curr[0]).toCharArray();
for(int i=0;i<4;i++){
for(char ch='0';ch<='9';ch++){
char prevChar = arr[i];
arr[i]=ch;
int newNum = Integer.parseInt(new String(arr));
if(!vis[newNum] && prime[newNum] && newNum>=1000){
vis[newNum]=true;
q.add(new int[]{newNum,curr[1]+1});
}
arr[i]=prevChar;
}
}
}
return -1;
}
}