C++ Concise solution with comments:  time-N^3; Memory: N^2
1) Intruducing and calculating two grids for storing prefix sum on columns & rows rescpectively.  \n2) Checking all sub-grids from bigger size down, verifying a
1) Intruducing and calculating two grids for storing prefix sum on columns & rows rescpectively.  \n2) Checking all sub-grids from bigger size down, verifying all four edges to see all of them are with 1\'s \n~~~\nclass Solution {\npublic:\n    int largest1BorderedSquare(vector<vector<int>>& grid) {\n        int m = grid.size(), n = grid[0].size();\n        // prefix sum on columns\n        vector<vector<int>> sumC(m, vector<int>(n + 1, 0));\n        // prefix sum on rows\n        vector<vector<int>> sumR(m + 1, vector<int>(n, 0));\n        for (int i = 0; i < m; ++i) {\n            for (int j = 0; j < n; ++j) {\n                sumC[i][j + 1] = sumC[i][j] + grid[i][j];\n            }\n        }\n        for (int j = 0; j < n; ++j) {\n            for (int i = 0; i < m; ++i) {\n                sumR[i + 1][j] = sumR[i][j] + grid[i][j];\n            }\n        }\n        \n        // check all sub-grids from bigger size down\n        // by verifying if all four edges are all with 1\'s\n        for (int s = min(m, n); s > 0; --s) {\n            for (int i = 0; i < m; ++i) {\n                for (int j = 0; j < n; ++j) {\n                    if (s + i > m || s + j > n) continue;\n                    bool flag = true;\n                    if (sumR[s+i][j]     - sumR[i][j]     < s) flag = false;\n                    if (sumR[s+i][j+s-1] - sumR[i][j+s-1] < s) flag = false;\n                    if (sumC[i][j+s]     - sumC[i][j]     < s) flag = false;\n                    if (sumC[s+i-1][j+s] - sumC[s+i-1][j] < s) flag = false;\n                    if (flag == true) return s * s;\n                }\n            }\n        }\n        return 0;\n    }\n};\n~~~\n
[]