【问题描述】[简单]
【解答思路】
千万不要想复杂了 不是三维空间 是一维空间 !
本题要求将给定的二维数组中指定的「色块」染成另一种颜色。「色块」的定义是:直接或间接相邻的同色方格构成的整体。
可以发现,「色块」就是被不同颜色的方格包围的一个同色岛屿。我们从色块中任意一个地方开始,利用广度优先搜索或深度优先搜索即可遍历整个岛屿。
注意:当目标颜色和初始颜色相同时,我们无需对原数组进行修改。
1. 广度优先搜索
我们从给定的起点开始,进行广度优先搜索。每次搜索到一个方格时,如果其与初始位置的方格颜色相同,就将该方格加入队列,并将该方格的颜色更新,以防止重复入队。
注意:因为初始位置的颜色会被修改,所以我们需要保存初始位置的颜色,以便于之后的更新操作。
时间复杂度:O(NM) 空间复杂度:O(NM)
class Solution {int[] dx = {1, 0, 0, -1};int[] dy = {0, 1, -1, 0};public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {int currColor = image[sr][sc];if (currColor == newColor) {return image;}int n = image.length, m = image[0].length;Queue<int[]> queue = new LinkedList<int[]>();queue.offer(new int[]{sr, sc});image[sr][sc] = newColor;while (!queue.isEmpty()) {int[] cell = queue.poll();int x = cell[0], y = cell[1];for (int i = 0; i < 4; i++) {int mx = x + dx[i], my = y + dy[i];if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {queue.offer(new int[]{mx, my});image[mx][my] = newColor;}}}return image;}
}
2. 深度优先搜索
我们从给定的起点开始,进行深度优先搜索。每次搜索到一个方格时,如果其与初始位置的方格颜色相同,就将该方格的颜色更新,以防止重复搜索;如果不相同,则进行回溯。
注意:因为初始位置的颜色会被修改,所以我们需要保存初始位置的颜色,以便于之后的更新操作
时间复杂度:O(NM) 空间复杂度:O(NM)
class Solution {int[] dx = {1, 0, 0, -1};int[] dy = {0, 1, -1, 0};public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {int currColor = image[sr][sc];if (currColor != newColor) {dfs(image, sr, sc, currColor, newColor);}return image;}public void dfs(int[][] image, int x, int y, int color, int newColor) {if (image[x][y] == color) {image[x][y] = newColor;for (int i = 0; i < 4; i++) {int mx = x + dx[i], my = y + dy[i];if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {dfs(image, mx, my, color, newColor);}}}}
}
【总结】
1. 遍历方向
int[] dx = {1, 0, 0, -1};int[] dy = {0, 1, -1, 0};for (int i = 0; i < 4; i++) {int mx = x + dx[i], my = y + dy[i];}
2.边界条件
if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) boolean inArea(int[][] image, int x, int y) {return x >= 0 && x < image.length&& y >= 0 && y < image[0].length;
}
3.遍历方向+边界条件 一维平面图遍历思路
转载链接:https://leetcode-cn.com/problems/flood-fill/solution/tu-xiang-xuan-ran-by-leetcode-solution/