Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LC_3240. Minimum Number of Flips to Make Binary Grid Palindromic II #191

Open
murane opened this issue Sep 1, 2024 · 0 comments
Open

LC_3240. Minimum Number of Flips to Make Binary Grid Palindromic II #191

murane opened this issue Sep 1, 2024 · 0 comments
Assignees
Labels

Comments

@murane
Copy link
Contributor

murane commented Sep 1, 2024

Problem link

https://leetcode.com/problems/minimum-number-of-flips-to-make-binary-grid-palindromic-ii/description/

Problem Summary

image

Solution

Source Code

import kotlin.math.min

class LC_3240 {
    fun minFlips(grid: Array<IntArray>): Int {
        val row = grid.size
        val col = grid[0].size

        var totalOnes = 0
        var flips = 0
        var diff = 0

        for (i in 0..<row / 2) {
            for (j in 0..<col / 2) {
                val onesCount =
                    grid[i][j] + grid[i][col - 1 - j] + grid[row - 1 - i][j] + grid[row - 1 - i][col - 1 - j]
                flips += min(onesCount, (4 - onesCount))
            }
        }

        if (col % 2 > 0) {
            for (i in 0..<row / 2) {
                if (grid[i][col / 2] != grid[row - 1 - i][col / 2]) {
                    diff++
                }
                totalOnes += grid[i][col / 2] + grid[row - 1 - i][col / 2]
            }
        }

        if (row % 2 > 0) {
            for (j in 0..<col / 2) {
                if (grid[row / 2][j] != grid[row / 2][col - 1 - j]) {
                    diff++
                }
                totalOnes += grid[row / 2][j] + grid[row / 2][col - 1 - j]
            }
        }

        if (col % 2 > 0 && row % 2 > 0) {
            flips += grid[row / 2][col / 2]
        }

        if (diff == 0 && totalOnes % 4 > 0) {
            flips += 2
        }

        return (flips + diff)
    }
}
@murane murane added the SOLVED label Sep 1, 2024
@murane murane self-assigned this Sep 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: To do
Development

No branches or pull requests

1 participant