λ¬Έμ
νμ΄ κ³Όμ
μ£Όμ΄μ§ martix
μμμ κ°μ₯ ν° μ μ¬κ°νμ μ°Ύλ λ¬Έμ μ
λλ€.
κ°κ°μ μ μ¬κ°νμ λλ€λ₯Έ μ μ¬κ°νμΌλ‘ ꡬμ±λμ΄ μλ€λ μ μ ν΅ν΄ λμ κ³νλ²
μΌλ‘ νμ΄κ° κ°λ₯ν λ¬Έμ μ
λλ€.
λ°λΌμ dp(x, y) = (x, y)λ₯Ό μΌμͺ½ λͺ¨μλ¦¬λ‘ νλ μ΅λ μ μ¬κ°νμ ν λ³μ κΈΈμ΄
λΌκ³ μ μνλ€λ©΄
λ€μκ³Ό κ°μ μ νμμ μΈμΈ μ μμ΅λλ€.
dp(x,y) = 0 if board[x][y] == 0 else min(dp(x+1, y), dp(x+1, y+1), dp(x, y+1)) + 1
μ΄λ board
μ κ° μ§μ μ μννλ©° 1μ΄ λ°κ²¬λ λλ§λ€ dp
λ₯Ό νΈμΆνλ©° μ΅λκ°μ κ°±μ νλ©΄ μνλ κ²°κ³Όλ₯Ό μ»μ μ μμ΅λλ€.
μ½λ
/**
* @param {character[][]} matrix
* @return {number}
*/
var maximalSquare = function (matrix) {
if (matrix.length === 0) {
return 0;
}
const H = matrix.length;
const W = matrix[0].length;
const memo = new Array(H).fill(null).map((_) => new Array(W).fill(-1));
function dp(x, y) {
if (x < 0 || x >= H || y < 0 || y >= W) {
return 0;
}
if (memo[x][y] !== -1) {
return memo[x][y];
}
if (matrix[x][y] === "1") {
memo[x][y] = Math.min(dp(x + 1, y), dp(x + 1, y + 1), dp(x, y + 1)) + 1;
} else {
memo[x][y] = 0;
}
return memo[x][y];
}
// κ°μ₯ ν° μ μ¬κ°νμ μ°Ύλλ€.
let ans = 0;
for (let x = 0; x < H; x++) {
for (let y = 0; y < W; y++) {
if (matrix[x][y] === "1") {
ans = Math.max(ans, dp(x, y));
}
}
}
return ans * ans;
};
const matrix = [
["1", "1", "1", "1", "1"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"],
];
console.log(maximalSquare(matrix));
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 101 - Symmetric Tree (Easy) (0) | 2021.03.02 |
---|---|
LeetCode 876 - Middle of the Linked List (Easy) (0) | 2021.03.02 |
LeetCode 543 - Diameter of Binary Tree (Easy) (1) | 2021.03.02 |
LeetCode 283 - Move Zeroes (Medium) (0) | 2021.03.02 |
LeetCode 678 - Valid Parenthesis String (Medium) (0) | 2021.03.02 |
π¬ λκΈ