想法:
優勢:
避免遞迴深度過大 Java遞迴層數太深會導致 StackOverflowError,因此BFS 使用 Queue,不受遞迴限制
程式碼:
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
int originalColor = image[sr][sc]; // 起點原始顏色
if (originalColor == color) return image; // 若已是目標顏色則不用處理
int rows = image.length;
int cols = image[0].length;
// 方向陣列:上、下、左、右
int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}};
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{sr, sc});
image[sr][sc] = color; // 起點先上色
while (!queue.isEmpty()) {
int[] current = queue.poll();
int r = current[0];
int c = current[1];
// 探索四個方向
for (int[] d : directions) {
int nr = r + d[0];
int nc = c + d[1];
// 邊界與顏色檢查
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && image[nr][nc] == originalColor) {
image[nr][nc] = color; // 塗色
queue.offer(new int[]{nr, nc}); // 加入佇列
}
}
}
return image;
}
}
比較:
BFS(佇列):
DFS(遞迴/堆疊):