Problem 170
Flood Fill
Easy · 10 pts · Matrix, Depth-First Search, Breadth-First Search
Problem
An image is a grid of R rows and C columns of integer colours. Starting from the pixel at row SR and column SC (zero-based), perform a flood fill with the new colour K: the starting pixel, and every pixel connected to it horizontally or vertically through pixels of the same original colour, is repainted with K. Print the resulting image. Use BFS or DFS from the starting pixel, visiting only neighbours that have the original colour. If K equals the original colour, nothing changes, and you must take care not to loop forever.
Input
First line: integers R and C. Next R lines: C integers. Last line: integers SR, SC (zero-based) and K.
Output
Print R lines with C space-separated integers.
Constraints
1 <= R, C <= 50; 0 <= color, K < 65536
Example input
3 3 1 1 1 1 1 0 1 0 1 1 1 2
Example output
2 2 2 2 2 0 2 0 1
Explanation
The fill starts at row 1, column 1, the centre, whose colour is 1. Every 1 connected to it (the top row, the left column and the centre) becomes 2. The 1 in the bottom-right corner is surrounded by 0's, so it is not connected and stays 1.