A row or column is considered palindromic if its values read the same forward and backward.
You can flip any number of cells in grid from 0 to 1, or from 1 to 0.
Return the minimum number of cells that need to be flipped to make all rows and columns palindromic, and the total number of 1’s in griddivisible by 4.
fromtypingimportListclassSolution:defminFlips(self,grid:List[List[int]])->int:m=len(grid)n=len(grid[0])m_half=m>>1n_half=n>>1flip_count=0# Four-cells groups.foriinrange(m_half):forjinrange(n_half):s=grid[i][j]+grid[i][-j-1]+grid[-i-1][j]+grid[-i-1][-j-1]flip_count+=min(s,4-s)# Center cell.ifm&1&n:flip_count+=grid[m_half][n_half]# Two-cells pairs (in middle row and middle column).one_one=0# The number of 1-1 pairs (mod 2).zero_one=0# The number of 0-1 and 1-0 pairs.ifm&1:forjinrange(n_half):s=grid[m_half][j]+grid[m_half][-j-1]one_one^=(s>>1)zero_one+=(s&1)ifn&1:foriinrange(m_half):s=grid[i][n_half]+grid[-i-1][n_half]one_one^=(s>>1)zero_one+=(s&1)flip_count+=zero_oneifzero_one>0else(one_one<<1)returnflip_count
评论需要 JavaScript。