Flood Fill

Practice this coding question on Coding Gurukul.

Problem statement

A pixel editor fills a connected patch selected by the artist. Only pixels connected through shared edges to the starting pixel, and having its original color, belong to the patch; a matching color elsewhere in the image is not enough. Your task Recolor every pixel in the four-directionally connected component of (sr, sc) to newColor. Membership is determined using the starting pixel's color before any changes. Important details Coordinates are zero-based. Diagonal contact does not connect regions. If newColor equals the original color, the image stays unchanged. Pixels outside the selected component retain their colors. Worked example For rows [1, 1] and [1, 2], starting at (0, 0) with newColor 3 changes the three connected 1s to 3. The lower-right 2 remains unchanged.

Input format

First line: rows columns sr sc newColor. Next rows lines: the image values.

Output format

Print the resulting matrix, one row per line with spaces between values.

Constraints

1 <= rows, columns <= 50; coordinates are valid; 0 <= colors <= 65535.

Sample input

2 2 0 0 3
1 1
1 2

Sample output

3 3
3 2

Sign in to run or submit a solution in C++, Java or Python.