Skills101
← All coding problems

Flood Fill

easyGraphs+10 XPTime limit 2s

An image is a grid of colour numbers. Starting from pixel (sr, sc), flood fill with color: change the start pixel and every pixel connected to it up, down, left or right through pixels of the same original colour.

Input:

  • line 1: r c
  • next r lines: c integers each
  • last line: sr sc color

Output: the image after the fill, one row per line.

Constraints: 1 ≤ r, c ≤ 300, 0 ≤ colour ≤ 9, 0 ≤ sr < r, 0 ≤ sc < c.

Watch out: if color equals the original colour, nothing changes — and a naive DFS would loop forever. Large one-colour images make deep recursion overflow; an explicit stack or queue is safest.

Sample input 1

3 3
1 1 1
1 1 0
1 0 1
1 1 2

Sample output 1

2 2 2
2 2 0
2 0 1

Sample input 2

2 3
0 0 0
0 0 0
0 0 0

Sample output 2

0 0 0
0 0 0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.