|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given a matrix with each grid a color type. Start from a random point, find |
| 5 | + * the perimeter of the region of the same color. |
| 6 | + * |
| 7 | + * Tags: BFS |
| 8 | + */ |
| 9 | +class MatrixColor { |
| 10 | + public static void main(String[] args) { |
| 11 | + MatrixColor m = new MatrixColor(); |
| 12 | + int[][] mat = { |
| 13 | + {2, 2, 1, 2}, |
| 14 | + {2, 2, 1, 2}, |
| 15 | + {2, 1, 1, 2}, |
| 16 | + {2, 2, 1, 2}, |
| 17 | + }; |
| 18 | + System.out.println(m.findPerimeter(mat, 0, 2)); |
| 19 | + System.out.println(m.findPerimeter(mat, 0, 1)); |
| 20 | + System.out.println(m.findPerimeter(mat, 0, 3)); |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * BFS |
| 25 | + * Add the start point to a queue, and set it as visited |
| 26 | + * Convert 2d coordinate to 1d integer and store it in queue |
| 27 | + * While the queue is not empty, get an integer from the queue |
| 28 | + * Convert it back to 2d and search the 4 cells around it |
| 29 | + * If within board, and not visited, add it to queue and set visited |
| 30 | + * If not same color, add edge count |
| 31 | + * If not within board, add edge count |
| 32 | + */ |
| 33 | + public int findPerimeter(int[][] mat, int x, int y) { |
| 34 | + if (mat == null || mat.length == 0 || mat[0].length == 0) return 0; |
| 35 | + |
| 36 | + Queue<Integer> q = new LinkedList<Integer>(); |
| 37 | + int m = mat.length; |
| 38 | + int n = mat[0].length; |
| 39 | + boolean[][] visited = new boolean[m][n]; |
| 40 | + int[][] dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; |
| 41 | + |
| 42 | + q.add(x * n + y); |
| 43 | + visited[x][y] = true; |
| 44 | + int perimeter = 0; |
| 45 | + while (!q.isEmpty()) { |
| 46 | + int size = q.size(); |
| 47 | + for (int i = 0; i < size; i++) { |
| 48 | + int pos = q.poll(); |
| 49 | + int curX = pos / n; |
| 50 | + int curY = pos % n; |
| 51 | + // update perimeter |
| 52 | + // System.out.println("curX: " + curX + " curY: " + curY); |
| 53 | + int count = 0; |
| 54 | + for (int[] d : dir) { |
| 55 | + int nX = curX + d[0]; |
| 56 | + int nY = curY + d[1]; |
| 57 | + if (nX >= 0 && nX < m && nY >= 0 && nY < n) { |
| 58 | + if (mat[nX][nY] == mat[x][y]) { |
| 59 | + if (!visited[nX][nY]) { |
| 60 | + q.add(nX * n + nY); |
| 61 | + visited[nX][nY] = true; |
| 62 | + } |
| 63 | + } else count++; |
| 64 | + } |
| 65 | + else count++; |
| 66 | + } |
| 67 | + perimeter += count; |
| 68 | + // System.out.println("count: " + count + " p: " + perimeter); |
| 69 | + } |
| 70 | + } |
| 71 | + return perimeter; |
| 72 | + } |
| 73 | +} |
0 commit comments