二、边框着色 (Weekly Contest 134)

给出一个二维整数网格 grid,网格中的每个值表示该位置处的网格块的颜色。

只有当两个网格块的颜色相同,而且在四个方向中任意一个方向上相邻时,它们属于同一连通分量。

连通分量的边界是指连通分量中的所有与不在分量中的正方形相邻(四个方向上)的所有正方形,或者在网格的边界上(第一行/列或最后一行/列)的所有正方形。

给出位于 (r0, c0) 的网格块和颜色 color,使用指定颜色 color 为所给网格块的连通分量的边界进行着色,并返回最终的网格 grid 。

示例 1:

输入:grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
输出:[[3, 3], [3, 2]]
示例 2:

输入:grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
输出:[[1, 3, 3], [2, 3, 3]]
示例 3:

输入:grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
输出:[[2, 2, 2], [2, 1, 2], [2, 2, 2]]

提示:

1 <= grid.length <= 50
1 <= grid[0].length <= 50
1 <= grid[i][j] <= 1000
0 <= r0 < grid.length
0 <= c0 < grid[0].length
1 <= color <= 1000

把题目读懂:是把连通中的涂上,就是和非连通分量中的,或者是边界都涂上
代码:

class Solution {
    public int[][] colorBorder(int[][] grid, int r0, int c0, int color) {
     int x[] = {0,0,-1,1};
		int y[] = {1,-1,0,0};
		Queue<int[]> tem = new LinkedList<>();
		int get = grid[r0][c0];
		int visit[][] = new int[grid.length][grid[0].length];
		visit[r0][c0] = 1;
		tem.offer(new int[]{r0,c0});
		List<int[]> list = new ArrayList();
		while (!tem.isEmpty()) {
			int tems[] = tem.poll();
            			System.out.println(Arrays.toString(tems));

			int x1 = tems[0];
			int y1 = tems[1];
			boolean flag = false;
			if(x1 == 0 || y1 == 0 || x1 == grid.length - 1|| y1 == grid[0].length - 1 ){
				flag = true;
			}
			for (int i = 0; i < 4; i++) {
				int temx = x1 + x[i];
				int temy = y1 + y[i];
				if(!(temx < 0 || temx >= grid.length || temy < 0 || temy >= grid[0].length)){
					if(grid[temx][temy] == get && visit[temx][temy] == 0 ){
						visit[temx][temy] = 1;
						tem.offer(new int[]{temx,temy});
						

						
					}
//					判断不是不有非连通
					if(!flag){
						if(grid[x1][y1] != grid[temx][temy])
						flag = true;
					}
				}
			}
			if(flag){
				list.add(new int[]{x1,y1});
			}
			
		}
		
		for (int[] is : list) {
			int temx = is[0];
			int temy = is[1];
			grid[temx][temy] = color;
		}
		return grid;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值