avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

221Maximum square

  2024-01-01        
字数统计: 390字   |   阅读时长: 2min

topic:

2023-02-01.png
221. Maximum square

Thought:

可以使用Dynamic planning降低时间复杂度。we use dp(i,j) Express (i,j) The lower right corner,Only contain 1 The maximum value of the side length of the square。If we can calculate all dp(i,j) Value,Then the maximum value is that it is only included in the matrix 1 The maximum value of the side length of the square,其平方即为Maximum square的面积。

So how to calculate dp Each element value?For each position (i,j),检查在矩阵中该位置Value:

if该位置Value是 0,but dp(i,j)=0,Because the current location cannot 1 Folk formation of composition;

if该位置Value是 1,but dp(i,j) Value由其上方、Three adjacent locations on the left and upper left dp Value decision。in particular,The element value of the current position is equal to the minimum value of the three adjacent elements 1,The state transfer equation is as follows:

dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1
also,You also need to consider boundary conditions。if i and j At least one of them is 0,but以位置(i,j) The lower right corner的Maximum square的边长只能是 1,therefore dp(i,j)=1
fig1

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

func maximalSquare(matrix [][]byte) int {
dp := make([][]int, len(matrix))
maxSide := 0
for i := 0; i < len(matrix); i++ {
dp[i] = make([]int, len(matrix[i]))
for j := 0; j < len(matrix[i]); j++ {
dp[i][j] = int(matrix[i][j] - '0')
if dp[i][j] == 1 {
maxSide = 1
}
}
}
for i := 1; i < len(matrix); i++ {
for j := 1; j < len(matrix[i]); j++ {
if dp[i][j] == 1 {
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1
if dp[i][j] > maxSide {
maxSide = dp[i][j]
}
}
}
}
return maxSide * maxSide
}

func min(x, y int) int {
if x < y {
return x
}
return y
}

  • Python
  • answer
  • Dynamic planning
  • golang

扫一扫,分享到微信

微信分享二维码
219.Existing duplicate elements II Hash table graphics
One question daily 2283
目录
  1. 1. topic:
  2. 2. Thought:
  3. 3. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号