内容中心

2026年评价高的低噪音永磁离心风机高口碑厂家推荐(评价高)-熙诚环保科技(苏州)有限公司

To solve this problem, we need to count the number of palindromic square submatrices in a given matrix. A square submatrix is palindromic if it is symmetric around its center.

Approach

  1. 1x1 Submatrices: Every single element in the matrix is a palindromic submatrix, so we start by initializing all entries in our DP table to 1 (since each 1x1 submatrix is valid).
  2. Larger Square Submatrices: For squares of size greater than 1, we check if the current square can be extended from a smaller palindromic square. Specifically, a square of size s ending at position (i, j) is palindromic if:
    • The elements at the four corners of the square are equal.
    • The inner square (of size s-2) ending at position (i-1, j-1) is palindromic.
  3. DP Table: We use a DP table where dp[i][j] represents the size of the largest palindromic square ending at (i, j). The value of dp[i][j] is determined by the minimum of:
    • The size of the inner square plus 2 (to extend it).
    • The maximum possible size of the square that can fit in the matrix from the top-left to (i, j).

Solution Code

m, n = map(int, input().split())
matrix = [input().strip() for _ in range(m)]

dp = [[1] * n for _ in range(m)]
total = 0

for i in range(m):
    for j in range(n):
        if i > 0 and j > 0:
            if matrix[i][j] == matrix[i-1][j-1] and matrix[i][j-1] == matrix[i-1][j]:
                dp[i][j] = min(dp[i-1][j-1] + 2, i+1, j+1)
            else:
                dp[i][j] = 1
        total += dp[i][j]

print(total)

Explanation

  • Initialization: The DP table dp is initialized to 1 because every 1x1 submatrix is a palindrome.
  • DP Transition: For each cell (i, j) (starting from the second row and second column), we check if the current cell can form a larger palindromic square. If the four corners are equal and the inner square is valid, we extend the size of the palindrome.
  • Summing Up: The total number of palindromic submatrices is the sum of all values in the DP table. This is because each entry dp[i][j] gives the count of palindromic squares ending at (i, j) (from size 1 up to the largest valid size).

This approach efficiently computes the result in O(m*n) time and space, making it suitable for large matrices. The solution leverages dynamic programming to avoid redundant calculations and ensures optimal performance.

熙诚环保科技(苏州)有限公司

熙诚环保科技(苏州)有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?