Skip to content

Commit 698146b

Browse files
committed
A solution added for LC #3905
1 parent 3ee0a3b commit 698146b

2 files changed

Lines changed: 105 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package org.sean.graph;
2+
3+
import java.util.ArrayDeque;
4+
import java.util.Deque;
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
/***
9+
* 3905. Multi Source Flood Fill
10+
*/
11+
public class MultiSrcFloodFill {
12+
13+
public int[][] colorGrid(int n, int m, int[][] sources) {
14+
int[][] grid = new int[n][m];
15+
16+
Deque<int[]> deque = new ArrayDeque<>();
17+
18+
for (int[] src : sources) {
19+
int r = src[0];
20+
int c = src[1];
21+
grid[r][c] = src[2];
22+
23+
// add all sources
24+
deque.add(new int[]{r, c});
25+
}
26+
27+
int[][] offsets = new int[][]{
28+
{-1, 0}, {0, 1}, {1, 0}, {0, -1}
29+
};
30+
31+
int step = 0;
32+
// <loc, step>
33+
Map<Integer, Integer> cache = new HashMap<>();
34+
35+
// BFS
36+
while (!deque.isEmpty()) {
37+
int sz = deque.size();
38+
39+
step++;
40+
for (int i = 0; i < sz; i++) {
41+
int[] grp = deque.poll();
42+
43+
if (grp == null) continue;
44+
int currRow = grp[0];
45+
int currCol = grp[1];
46+
int currVal = grid[currRow][currCol];
47+
48+
for (int[] off : offsets) {
49+
int nRow = currRow + off[0];
50+
int nCol = currCol + off[1];
51+
if (nRow >= n || nRow < 0 || nCol >= m || nCol < 0)
52+
continue;
53+
54+
// at the same time step
55+
int nextStep = step + 1;
56+
int key = nRow * m + nCol;
57+
58+
if (grid[nRow][nCol] == 0) {
59+
grid[nRow][nCol] = currVal;
60+
cache.put(key, nextStep);
61+
62+
// added once for next round coloring
63+
deque.add(new int[]{nRow, nCol});
64+
} else {
65+
if (cache.getOrDefault(key, 0) == nextStep
66+
&& grid[nRow][nCol] < currVal) {
67+
grid[nRow][nCol] = currVal;
68+
}
69+
}
70+
}
71+
72+
}
73+
}
74+
75+
return grid;
76+
}
77+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.sean.graph;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
import static org.junit.Assert.assertArrayEquals;
8+
9+
public class MultiSrcFloodFillTest {
10+
11+
private MultiSrcFloodFill floodFill;
12+
13+
@Before
14+
public void setUp() throws Exception {
15+
floodFill = new MultiSrcFloodFill();
16+
}
17+
18+
@Test
19+
public void colorGrid() {
20+
int[][] res = floodFill.colorGrid(3, 3, new int[][]{
21+
{0, 1, 3}, {1, 1, 5}
22+
});
23+
24+
assertArrayEquals(new int[][]{
25+
{3, 3, 3}, {5, 5, 5}, {5, 5, 5}
26+
}, res);
27+
}
28+
}

0 commit comments

Comments
 (0)