You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions.
The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).
You should color the border of the connected component that contains the square grid[row][col] with color.
Return the final grid.
给定一个 m x n 整数矩阵网格,以及三个整数 row、col 和 color。 网格中的每个值代表该位置的网格方块的颜色。
如果两个格子具有相同的颜色并且在 4 个方向中的任何一个方向上彼此相邻,则它们属于同一个连通分量。
连通分量的边界是连通分量中与不在该分量中的正方形在 4 方向上相邻的所有正方形,或者在网格边界(第一行或最后一行或列)上的所有正方形。
您应该使用颜色为包含方形 grid[row][col] 的连通分量的边界着色。
返回最终网格。
示例 1:
输入:grid = [[1,1],[1,2]], row = 0, col = 0, color = 3 输出:[[3,3],[3,2]] 示例 2:
输入:grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3 输出:[[1,3,3],[2,3,3]] 示例 3:
输入:grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2 输出:[[2,2,2],[2,1,2],[2,2,2]]
提示:
m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j], color <= 1000 0 <= row < m 0 <= col < n
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/co… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int[][] colorBorder(int[][] grid, int row, int col, int color) {
int m = grid.length, n = grid[0].length;//m是行数,n是列数
int[][] ans = new int[m][n]; //ans用来在广度搜索的过程中进行着色和避免重复走已经走过的位置
int[][] dirs = new int[][]{{1,0}, {-1,0}, {0,1}, {0,-1}};//上下左右的走法
Deque<int[]> d = new ArrayDeque<>();//创建队列
d.addLast(new int[]{row, col});//用队列记录坐标
while (!d.isEmpty()) {
int[] poll = d.pollFirst();//取出一个坐标
int x = poll[0], y = poll[1], cnt = 0;
for (int[] di : dirs) {//上下右左开始遍历 广度搜索
int nx = x + di[0], ny = y + di[1];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;//如果越界了就证明要换一个方向了
if (grid[x][y] != grid[nx][ny]) continue;//如果颜色不一样就不能走了,需要换一个方向
else cnt++;//如果下一步的位置和原来的位置颜色一样,那么用cnt记录上下左右颜色相同位置的个数
if (ans[nx][ny] != 0) continue;//如果下一步被走过了就继续换一个方向(此时知道了这个位置已经被走过了就不用再走第二次了)
d.addLast(new int[]{nx, ny});//所以就继续把没有走过的地方加入到队列中
}
ans[x][y] = cnt == 4 ? grid[x][y] : color;//如果上下左右都是颜色相同的位置,那么就可以赋值原来的数字,如果不是4说明这个位置是边界,则就将其染色。
}
//然后将其他没有赋值的位置赋值
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (ans[i][j] == 0) ans[i][j] = grid[i][j];
}
}
return ans;
}
}
作者:AC_OIer
链接:https://leetcode-cn.com/problems/coloring-a-border/solution/gong-shui-san-xie-tu-lun-sou-suo-zhuan-t-snvw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 广度搜索和队列的结合
- 此题使用了逆向思维,一般看到这题可能会用边界的条件作为搜索的结束条件
- 但是我们可以换个角度去思考,连通分量除了边界,就剩下了内部被边界包围的地方,这些地方有一个共同点就是上下左右都是相同的颜色。这也是可以当作搜索的结束条件的。