BFS 02

69 阅读1分钟

LeetCode 733

leetcode-cn.com/problems/fl…

代码如下

class Solution {
	int[] dx = { -1, 1, 0, 0 };
	int[] dy = { 0, 0, -1, 1 };

	public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
		int preColor = image[sr][sc];
		if (preColor == newColor) {
			return image;
		}
		int n = image.length, m = image[0].length;
		Deque<int[]> queue = new LinkedList<int[]>(); // 队列,维护bfs
		queue.offer(new int[] { sr, sc });
		image[sr][sc] = newColor;
		
		while (!queue.isEmpty()) {
			int[] now = queue.poll();
			int x = now[0], y = now[1];
			for (int i = 0; i < 4; i++) {
				int newX = x + dx[i], newY = y + dy[i];
				if (newX >= 0 && newX < n && newY >= 0 && newY < m && image[newX][newY] == preColor) {
					queue.offer(new int[] {newX, newY});
					image[newX][newY] = newColor;
				}
			}
		}
		return image;
	}
//	public static void main(String[] args) {
//		Solution k = new Solution();
//		int[][] a = new int[][] { { 1, 1, 1 }, { 1, 1, 0 }, { 1, 0, 1 } };
//		System.out.println(Arrays.deepToString(k.floodFill(a, 1, 1, 2)));
//	}
}