3240. 最少翻转次数使二进制矩阵回文 II

Powered by:NEFU AB-IN

Link

文章目录

  • [3240. 最少翻转次数使二进制矩阵回文 II](#3240. 最少翻转次数使二进制矩阵回文 II)

3240. 最少翻转次数使二进制矩阵回文 II

题意

给你一个 m x n 的二进制矩阵 grid 。

如果矩阵中一行或者一列从前往后与从后往前读是一样的,那么我们称这一行或者这一列是 回文 的。

你可以将 grid 中任意格子的值 翻转 ,也就是将格子里的值从 0 变成 1 ,或者从 1 变成 0 。

请你返回 最少 翻转次数,使得矩阵中 所有 行和列都是 回文的 ,且矩阵中 1 的数目可以被 4 整除 。

思路

并查集+思维+dp

  1. 如果一个数变的话,为了保持回文,那么行对称和列对称的两个数也得变(其实是四个数),所以这就形成了一个集合,且集合与集合之间互不影响
  2. 即使用并查集维护,并维护集合中1的个数和集合大小
  3. 使用dp状态机,dp[i]表示:1的数量 %4=i 的最小操作次数,当遇到根节点,对集合针对0和1都进行翻转,因为集合只能全为0和1
  4. 拓展性更强,把4的倍数改成 2 3 4 5 6 7 8 9 的倍数都没关系

代码

python 复制代码
'''
Author: NEFU AB-IN
Date: 2024-08-07 10:04:41
FilePath: \LeetCode\3240\3240.py
LastEditTime: 2024-08-07 11:06:07
'''
# 3.8.19 import
import random
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush, nlargest, nsmallest
from itertools import combinations, compress, permutations, starmap, tee
from math import ceil, comb, fabs, floor, gcd, hypot, log, perm, sqrt
from string import ascii_lowercase, ascii_uppercase
from sys import exit, setrecursionlimit, stdin
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union

# Constants
TYPE = TypeVar('TYPE')
N = int(2e5 + 10)
M = int(20)
INF = int(1e12)
OFFSET = int(100)
MOD = int(1e9 + 7)

# Set recursion limit
setrecursionlimit(int(2e9))


class Arr:
    array = staticmethod(lambda x=0, size=N: [x() if callable(x) else x for _ in range(size)])
    array2d = staticmethod(lambda x=0, rows=N, cols=M: [Arr.array(x, cols) for _ in range(rows)])
    graph = staticmethod(lambda size=N: [[] for _ in range(size)])


class Math:
    max = staticmethod(lambda a, b: a if a > b else b)
    min = staticmethod(lambda a, b: a if a < b else b)


class IO:
    input = staticmethod(lambda: stdin.readline().rstrip("\r\n"))
    read = staticmethod(lambda: map(int, IO.input().split()))
    read_list = staticmethod(lambda: list(IO.read()))


class Std:
    class UnionFind:
        """Union-Find data structure."""

        def __init__(self, n):
            self.n = n
            self.parent = list(range(n))  # Parent pointers
            self.rank = Arr.array(1, n)  # Rank (approximate tree height)
            self.size = Arr.array(1, n)  # Size arrays for each node
            self.cnt_1 = Arr.array(0, n)

        def find(self, p):
            """Find the root of the element p with path compression."""
            if self.parent[p] != p:
                self.parent[p] = self.find(self.parent[p])  # Path compression
            return self.parent[p]

        def union(self, p, q):
            """Union the sets containing p and q using union by rank and merge data if available."""
            rootP = self.find(p)
            rootQ = self.find(q)

            if rootP != rootQ:
                # Union by rank
                if self.rank[rootP] > self.rank[rootQ]:
                    self.parent[rootQ] = rootP
                    self.size[rootP] += self.size[rootQ]
                    self.cnt_1[rootP] += self.cnt_1[rootQ]
                    return rootP
                elif self.rank[rootP] < self.rank[rootQ]:
                    self.parent[rootP] = rootQ
                    self.size[rootQ] += self.size[rootP]
                    self.cnt_1[rootQ] += self.cnt_1[rootP]
                    return rootQ
                else:
                    self.parent[rootQ] = rootP
                    self.size[rootP] += self.size[rootQ]
                    self.cnt_1[rootP] += self.cnt_1[rootQ]
                    self.rank[rootP] += 1
                    return rootP
            return rootP  # They are already in the same set

# --------------------------------------------------------------- Division line ------------------------------------------------------------------


class Solution:
    def minFlips(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        uf = Std.UnionFind(m * n)

        def index(i, j): return i * n + j

        for i in range(m):
            for j in range(n):
                uf.cnt_1[index(i, j)] = grid[i][j]

        for i in range(m):
            for j in range(n):
                uf.union(index(i, j), index(i, n - j - 1))
                uf.union(index(i, j), index(m - i - 1, j))

        dp = [0, INF, INF, INF]  # dp[i]表示:1的数量%4=i的最小操作次数
        for i in range(m):
            for j in range(n):
                if uf.find(index(i, j)) == index(i, j):
                    f = [INF] * 4
                    for x in range(4):  # 每个连通块内,要么全1,要么全0
                        # 全变为0,则需要将该连通块的所有1翻转
                        f[(x + 0) % 4] = Math.min(f[(x + 0) % 4], dp[x] + uf.cnt_1[index(i, j)])
                        # 全变为1,则需要将该连通块的所有0翻转,0的数量是总数量减1的数量
                        f[(x + uf.size[index(i, j)]) % 4] = Math.min(f[(x + uf.size[index(i, j)]) % 4], dp[x] + uf.size[index(i, j)] - uf.cnt_1[index(i, j)])
                    dp = f
        return dp[0]
相关推荐
Keying,,,,19 小时前
力扣hot100 | 矩阵 | 73. 矩阵置零、54. 螺旋矩阵、48. 旋转图像、240. 搜索二维矩阵 II
python·算法·leetcode·矩阵
易木木木响叮当2 天前
有限元方法中的数值技术:行列式、求逆、矩阵方程
线性代数·矩阵
东方佑3 天前
UniVoc:基于二维矩阵映射的多语言词汇表系统
人工智能·算法·矩阵
火车叨位去19493 天前
力扣top100(day01-05)--矩阵
算法·leetcode·矩阵
厦门辰迈智慧科技有限公司4 天前
现代化水库运行管理矩阵建设的要点
运维·网络·物联网·线性代数·安全·矩阵·监测
{⌐■_■}4 天前
【MongoDB】简单理解聚合操作,案例解析
数据库·线性代数·mongodb
文弱_书生4 天前
为什么神经网络的权重矩阵具有低秩特性?如何理解和解释?
人工智能·神经网络·矩阵
盛世隐者7 天前
【线性代数】线性方程组与矩阵——行列式
线性代数
盛世隐者7 天前
【线性代数】线性方程组与矩阵——(1)线性方程组与矩阵初步
线性代数
夜斗小神社7 天前
【LeetCode 热题 100】(六)矩阵
算法·leetcode·矩阵