构建框架
- 图的遍历
// (x, y) 为坐标位置
void fill(int x, int y) {
fill(x - 1, y); // 上
fill(x + 1, y); // 下
fill(x, y - 1); // 左
fill(x, y + 1); // 右
}
leedcode
- 颜色填充
- 问题描述:实现颜色填充功能,待填充的图像用二维数组 image 表示,元素为初始颜色值。初始坐标点的横坐标为 sr 纵坐标为 sc。需要填充的新颜色为 newColor
- 防止陷入死循环,必须到访问的位置进行标记
public void fill(int[][] image, int sr, int sc, int oldColor, int newColor) {
if(sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length) {
return;
}
if(image[sr][sc] != oldColor || image[sr][sc] == -1) {
return;
}
System.out.println(sr + " " + sc);
image[sr][sc] = -1;
fill(image, sr - 1, sc, oldColor, newColor);
fill(image, sr + 1, sc, oldColor, newColor);
fill(image, sr, sc - 1, oldColor, newColor);
fill(image, sr, sc + 1, oldColor, newColor);
image[sr][sc] = newColor;
}
- 矩阵中的路径(剑指offer-12)
- boolean ans = help(board, word, ind + 1, row - 1, col)
|| help(board, word, ind + 1, row, col + 1)
|| help(board, word, ind + 1, row + 1, col)
|| help(board, word, ind + 1, row, col - 1);- ||:当某一个为 true 时,将不再进行后续判断,无需做无用功