力扣刷题——733. 图像渲染
733. 图像渲染
用深度搜索完成,每改变一个色块之后就标记上色完成
package leetcode;
import java.util.Arrays;
public class T733 {
public static void main(String[] args) {
int image[][] = new int[][] {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
int sr = 1, sc = 1, newColor = 2;
new T733().new Solution().floodFill(image, sr, sc, newColor);
System.out.println(Arrays.deepToString(image));//遍历二维数组
}
class Solution {
boolean[][] flag = new boolean[50][50];// 默认初始化是false
int[] cr = new int[] { -1, 0, +1, 0 };// 水平方向偏移量
int[] cc = new int[] { 0, -1, 0, +1 };// 垂直方向偏移量
int pColor;// 初始位置色块的像素
int color;// 需要改成的色块像素
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
pColor = image[sr][sc];
this.color = color;
change(image, sr, sc);
return image;
}
public void change(int[][] image, int sr, int sc) {
if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length) {//检查边界
return;
}
if (image[sr][sc] == pColor && flag[sr][sc] == false) {// 如果色块符合并且未被标记过
image[sr][sc] = this.color;
flag[sr][sc] = true;
// 从起点遍历四个方向,注意不要写成双重循环了
for (int i = 0; i < cr.length; ++i) {
change(image, sr + cr[i], sc + cc[i]);
}
}
}
}
}
写题过程中在遍历四个方向时用了双重循环,运行发现代码有问题,调试了一会突然想到应该是单循环就够了。还得继续注意细节。
java语法技巧总结
java提供了工具遍历数组,不需要再手写循环遍历数组。遍历一维数组可以使用Arrays.toString(),二维数组可以使用Arrays.deepToString()。
posted on 2023-02-17 13:44 pumpkinsBig 阅读(31) 评论(0) 收藏 举报
浙公网安备 33010602011771号