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]
相关推荐
余~~1853816280016 小时前
矩阵碰一碰发视频的后端源码技术,支持OEM
线性代数·矩阵·音视频
CoderCodingNo17 小时前
【GESP】C++二级真题 luogu-b3924, [GESP202312 二级] 小杨的H字矩阵
java·c++·矩阵
@ V:ZwaitY0917 小时前
如何打造TikTok矩阵:多账号管理与内容引流的高效策略
人工智能·矩阵·tiktok
_Itachi__17 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
01_18 小时前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
curemoon1 天前
理解都远正态分布中指数项的精度矩阵(协方差逆矩阵)
人工智能·算法·矩阵
和光同尘@2 天前
74. 搜索二维矩阵(LeetCode 热题 100)
数据结构·c++·线性代数·算法·leetcode·职场和发展·矩阵
Vacant Seat2 天前
矩阵-矩阵置零
java·矩阵·二维数组
跨境卫士小树2 天前
店铺矩阵崩塌前夜:跨境多账号运营的3个生死线
大数据·线性代数·矩阵
BingLin-Liu3 天前
蓝桥杯备考:贪心算法之矩阵消除游戏
游戏·贪心算法·矩阵