-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEx 13.java
More file actions
98 lines (77 loc) · 2.41 KB
/
Ex 13.java
File metadata and controls
98 lines (77 loc) · 2.41 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.LinkedList;
import java.util.Queue;
import static java.lang.Integer.parseInt;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String vu = sc.nextLine();
Pattern pt = Pattern.compile("[^\\[ ]*\\[");
Matcher mch = pt.matcher(vu);
int radif = -1;
while (mch.find()) {
radif ++;
}
vu = vu.replaceAll("\\[" , "");
vu = vu.replaceAll("," , "");
vu = vu.replaceAll("\\]" , "");
int soton = vu.length() / radif;
char[] tmp = vu.toCharArray();
int[][] tb = new int[radif][soton];
int k=0;
for (int i=0 ; i<radif ; i++){
for(int j=0 ; j<soton ; j++){
tb[i][j] = parseInt(String.valueOf(tmp[k]));
k++;
}
}
int [][] h = new int[radif][soton];
h = bfs(tb ,radif ,soton);
String khuruji = "[";
for (int i = 0; i < radif; i++) {
khuruji += "[";
for (int j = 0; j < soton; j++) {
khuruji += h[i][j];
if(j<soton-1)
khuruji += ",";
}
khuruji += "]";
if(i<radif-1)
khuruji += ",";
}
khuruji += "]";
System.out.print(khuruji);
}
static int[][] bfs(int[][] cur , int radif , int soton){
Queue<int[]> BFS = new LinkedList<>();
int[][] H = new int[radif][soton];
for(int i = 0; i< radif; i++){
for(int j = 0; j< soton; j++){
if(cur[i][j] == 1){
H[i][j] = 0;
BFS.add(new int[]{i, j});
}
else{
H[i][j] = -1;
}
}
}
int[] dir = {0, 1, 0, -1, 0};
while(!BFS.isEmpty()){
int[] t = BFS.poll();
int r = t[0], s = t[1];
for(int i=0 ; i<4 ; i++){
int nr = r + dir[i];
int ns = s + dir[i+1];
if(nr < 0 || nr == radif || ns < 0 || ns == soton || H[nr][ns] != -1) {
continue;
}
H[nr][ns] = H[r][s] + 1;
BFS.add(new int[]{nr, ns});
}
}
return H;
}
}