Coding Skills - Flip with adjacent squares - Google

Software Engineering System Design
suifeng2006
Posts: 5
Joined: Sat Apr 23, 2022 12:12 pm

Coding Skills - Flip with adjacent squares - Google

Post by suifeng2006 »

Given a matrix with red and blue squares in it, you can only flip the top left square but there is a chain reaction, which is all the adjacent(up,down, left,right) squares of the same color are flipped accordingly.

Code: Select all

Example 1:
Input:
[0, 0, 1, 0]     flip     [1, 1, 1, 0]     flip     [0, 0, 0, 0]    flip    [1, 1, 1, 1]
[0, 1, 0, 1]   ------->   [1, 1, 0, 1]   ------->   [0, 0, 0, 1]  ------->  [1, 1, 1, 1]
[0, 1, 0, 1]              [1, 1, 0, 1]              [0, 0, 0, 1]            [1, 1, 1, 1]
Output: 3

Example 2:

Input:
[0, 0, 1, 0]     flip     [1, 1, 1, 0]     flip     [0, 0, 0, 0]
[0, 0, 0, 1]   ------->   [1, 1, 1, 1]   ------->   [0, 0, 0, 0]
[0, 1, 0, 1]              [1, 1, 1, 1]              [0, 0, 0, 0]
Output: 2

Question: After at least how many flips, you can make all squares one color?