Skip to content

3239. Minimum Number of Flips to Make Binary Grid Palindromic I 👍

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int minFlips(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    int rowFlips = 0;
    int colFlips = 0;

    for (const vector<int>& row : grid)
      for (int i = 0; i < n / 2; ++i)
        if (row[i] != row[n - 1 - i])
          ++rowFlips;

    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m / 2; ++i)
        if (grid[i][j] != grid[m - 1 - i][j])
          ++colFlips;

    return min(rowFlips, colFlips);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int minFlips(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    int rowFlips = 0;
    int colFlips = 0;

    for (int[] row : grid)
      for (int i = 0; i < n / 2; ++i)
        if (row[i] != row[n - 1 - i])
          ++rowFlips;

    for (int j = 0; j < n; ++j)
      for (int i = 0; i < m / 2; ++i)
        if (grid[i][j] != grid[m - 1 - i][j])
          ++colFlips;

    return Math.min(rowFlips, colFlips);
  }
}
1
2
3
4
5
6
7
class Solution:
  def minFlips(self, grid: list[list[int]]) -> int:
    rowFlips = sum(row[i] != row[-1 - i]
                   for row in grid for i in range(len(row) // 2))
    colFlips = sum(col[i] != col[-1 - i] for col in zip(*grid)
                   for i in range(len(col) // 2))
    return min(rowFlips, colFlips)