题目
给你一个大小为 m x n 的整数矩阵 grid ,表示一个网格。另给你三个整数 row、col 和 color 。网格中的每个值表示该位置处的网格块的颜色。
两个网格块属于同一 连通分量 需满足下述全部条件:
两个网格块颜色相同
在上、下、左、右任意一个方向上相邻
连通分量的边界 是指连通分量中满足下述条件之一的所有网格块:
在上、下、左、右四个方向上与不属于同一连通分量的网格块相邻
在网格的边界上(第一行/列或最后一行/列)
请你使用指定颜色 color 为所有包含网格块 grid[row][col] 的 连通分量的边界 进行着色,并返回最终的网格 grid 。
解题思路
用BFS找出连通分量,即从指定点出发只走颜色相同的地方。其边界要么是原数组的边界,要么是颜色不一样的地方。那么在走的过程中如果下一步会越界,或者下一步位置的颜色与当前位置不一样,则当前位置就是边界,需要改变其颜色。
代码
class gridNode {
int row, col;
public gridNode() {
}
public gridNode(int row, int col) {
this.row = row;
this.col = col;
}
}
class Solution {
public static final int[][] turn = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int[][] colorBorder(int[][] grid, int row, int col, int color) {
int lengthRow = grid.length, lengthCol = grid[0].length, preColor = grid[row][col];
boolean[][] flag = new boolean[lengthRow][lengthCol];
Queue<gridNode> queue = new ArrayDeque<>();
flag[row][col] = true;
gridNode begin = new gridNode(row, col);
queue.add(begin);
while (!queue.isEmpty()) {
gridNode now = queue.poll();
for (int i = 0; i < 4; i++) {
gridNode next = new gridNode(now.row + turn[i][0], now.col + turn[i][1]);
if (judge(next, lengthRow, lengthCol)) {
grid[now.row][now.col] = color;
continue;
}
if (flag[next.row][next.col]) continue;
if (grid[next.row][next.col] != preColor) {
grid[now.row][now.col] = color;
continue;
}
flag[next.row][next.col] = true;
queue.add(next);
}
}
return grid;
}
private boolean judge(gridNode next, int lengthRow, int lengthCol) {
return next.row < 0 || next.row >= lengthRow || next.col < 0 || next.col >= lengthCol;
}
}
别看代码略长,还是凎碎了82.67% / 83.66%的。