-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitmap.java
90 lines (85 loc) · 2.88 KB
/
Bitmap.java
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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* Created at : 23/10/21
* <p>
* <a href=https://www.spoj.com/problems/BITMAP/>BITMAP - Bitmap</a>
*
* @author Himanshu Shekhar
*/
public class Bitmap {
/**
* <strong>Multi-source BFS</strong>
* Similar to {@link leetcode.RottingOranges#orangesRotting(int[][])}
*/
private static int[][] bitmap(int[][] map, int m, int n) {
int[][] res = new int[m][n];
int[] d = {0, 1, 0, -1, 0};
Queue<int[]> src = new LinkedList<>();
// adding all sources i.e., "1's" into a queue
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == 1)
src.offer(new int[]{i, j});
else
res[i][j] = Integer.MAX_VALUE;
}
}
int currDist = 1; // dist. of adjacent cells containing "1" is 1
while (!src.isEmpty()) {
int size = src.size();
while (size-- > 0) {
int[] currSrc = src.poll();
int x = currSrc[0], y = currSrc[1];
for (int i = 0; i < 4; i++) {
int nextX = x + d[i], nextY = y + d[i + 1];
boolean inBound = (nextX >= 0 && nextX < m) && (nextY >= 0 && nextY < n);
// neighboring cells is 1 more than current distance from "1"
// store minimum distance from "1"
if (inBound && map[nextX][nextY] == 0 && res[nextX][nextY] > currDist) {
res[nextX][nextY] = currDist;
src.offer(new int[]{nextX, nextY});
}
}
}
// distance of neighboring cells increases as we move far from cell containing "1"
currDist++;
}
return res;
}
/**
* Method to print a 2-d array
*/
private static void print2DArray(int[][] arr) {
for (int[] row : arr) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
// taking inputs
int t = sc.nextInt();
while (t-- > 0) {
int m = sc.nextInt();
int n = sc.nextInt();
int[][] map = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = sc.nextInt();
}
}
// solving the problem
int[][] res = bitmap(map, m, n);
// printing the output
print2DArray(res);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}