|
| 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 | +} |
0 commit comments