[Java] 3 Lines algorithm solution + easy explanation! O(N*M) DP
\nclass Solution {\n    public int countSquares(int[][] matrix) {\n        int mat[][] = new int[matrix.length + 1][matrix[0].length + 1];\n        int sum = 0;
```\nclass Solution {\n    public int countSquares(int[][] matrix) {\n        int mat[][] = new int[matrix.length + 1][matrix[0].length + 1];\n        int sum = 0;\n        \n        /*  We can do Dynamic Programming by saving how many\n            Squares can be formed using the bottom right corner\n            element.\n        */\n        \n        for(int i = 1; i <= matrix.length; i++)\n            for(int j = 1; j <= matrix[0].length; j++)\n                if(matrix[i - 1][j - 1] != 0)\n                    sum += (mat[i][j] = Math.min(Math.min(mat[i - 1][j], mat[i][j - 1]), mat[i - 1][j - 1]) + 1);\n        \n                \n        /*\n        Workin on the first example:\n        ===========================\n        Matrix =\n        [0,1,1,1],\n        [1,1,1,1],\n        [0,1,1,1]\n        ===========================\n        mat after algorithm = \n        [0,0,0,0,0],\n        [0,0,1,1,1],\n        [0,1,1,2,2],\n        [0,0,1,2,3]\n        ===========================\n        After summing all indicies, now we get the correct answer!\n        */\n                \n        return sum;\n    }\n}\n```\n\n**Please upvote if you like it! **
[]