알고리즘/리트코드

1277. Count Square Submatrices with All Ones

창고 2021. 5. 23. 17:13

https://leetcode.com/problems/count-square-submatrices-with-all-ones/

 

Count Square Submatrices with All Ones - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

행렬에서 정사각형 개수 찾기

 

1. Brute Force

둘레를 따라서 탐색하기 = 대각선으로 탐색하기

오른쪽 아래 방향으로 진행

/**

 * @param {number[][]} matrix

 * @return {number}

 */

var countSquares = function (matrix) {

    let row = matrix[0].length;

    let col = matrix.length;

    let count = 0;

 

    for (let y = 0y < coly++) {

        for (let x = 0x < rowx++) {

            outerLoopfor (let i = 0y + i < col && x + i < rowi++, count++) {

                for (let j = 0j <= ij++) {

                    if (matrix[y + i][x + j] === 0 || matrix[y + j][x + i] === 0break outerLoop;

                }

            }

        }

    }

    return count;

};

 

2. 개선

특정 위치에서 만들 수 있는 사각형의 개수를 누적하여 기록

 

 

 

 

 

https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/442184/JavaScript-Easy-to-understand-2-solutions