classSolution: defcountSquares(self, matrix: List[List[int]]) -> int: m, n = len(matrix), len(matrix[0]) @cache defdfs(i, j): # 以 (i, j) 為右下角的最大正方形邊長 if i < 0or j < 0: return0 if matrix[i][j] == 0: return0 return1 + min(dfs(i - 1, j), dfs(i, j - 1), dfs(i - 1, j - 1)) ans = 0 for i inrange(m): for j inrange(n): ans += dfs(i, j) return ans
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intcountSquares(vector<vector<int>>& matrix){ int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> memo(m, vector<int>(n, -1)); auto dfs = [&](auto&& dfs, int i, int j) -> int { if (i < 0 || j < 0) return0; int& res = memo[i][j]; if (res != -1) return res; if (matrix[i][j] == 0) return res = 0; return res = 1 + min({dfs(dfs, i - 1, j), dfs(dfs, i, j - 1), dfs(dfs, i - 1, j - 1)}); }; int ans = 0; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) ans += dfs(dfs, i, j); return ans; } };
classSolution: defcountSquares(self, matrix: List[List[int]]) -> int: m, n = len(matrix), len(matrix[0]) f = [[0] * n for _ inrange(m)] for i inrange(m): for j inrange(n): if matrix[i][j] == 0: continue if i == 0or j == 0: f[i][j] = 1 else: f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1 returnsum(sum(row) for row in f)
classSolution { public: intcountSquares(vector<vector<int>>& matrix){ int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> f(m, vector<int>(n)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) continue; if (i == 0 || j == 0) { f[i][j] = 1; } else { f[i][j] = min({f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]}) + 1; } } } int ans = 0; for (constauto& row : f) ans += accumulate(row.begin(), row.end(), 0); return ans; } };
寫在最後
PROMPT
Mystical Moonlight Encounter: A young anime girl, dressed in a black cape and witch hat, holds a pumpkin with an intense gaze. Standing before a large window framing a moonlit night sky, her focus is riveted on the pumpkin. To her left, a vibrant yellow pumpkin sits atop a straw bale amidst autumn leaves, adding a burst of warmth to the enchanting scene.