#3071

Minimum Operations to Write the Letter Y on a Grid

specialist · 665 · lc medium +30 · verified · 64.4% accepted · 147 likes · top 68%

Description

A 0-indexed n x n grid (odd n) has cells valued 0, 1, or 2. A cell is part of the Letter Y if it lies on the top-left-to-center diagonal, the top-right-to-center diagonal, or the center-to-bottom vertical segment. The Letter Y is formed when:

- Every Y-cell shares the same value.

- Every non-Y-cell shares the same value.

- The Y-cell value differs from the non-Y-cell value.

In one operation you may set any cell to 0, 1, or 2. Return the minimum operations needed to form the Letter Y.

Example 1:

Input: grid = [[1,2,2],[1,1,0],[0,1,0]]
Output: 3
Explanation: We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.
It can be shown that 3 is the minimum number of operations needed to write Y on the grid.

Example 2:

Input: grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]
Output: 12
Explanation: We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2.
It can be shown that 12 is the minimum number of operations needed to write Y on the grid.

Code

1
2
3