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
- 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).
- 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
sending 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.
- 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 ofdp[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
dpis 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.


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