C++ | 91% faster | horizonatal and vertical precalculation
\nclass Solution {\npublic:\n    int largest1BorderedSquare(vector<vector<int>>& grid) {\n        vector<vector<int>> hb(grid.size(),vector<int>(grid[0].size(),
```\nclass Solution {\npublic:\n    int largest1BorderedSquare(vector<vector<int>>& grid) {\n        vector<vector<int>> hb(grid.size(),vector<int>(grid[0].size(),0));\n        vector<vector<int>> vb(grid.size(),vector<int>(grid[0].size(),0));\n        for(int i = 0;i<grid.size();i++)\n        {\n            for(int j = 0;j<grid[0].size();j++)\n            {\n                if(grid[i][j]==1)\n                {\n                if(j>0)\n                {\n                    hb[i][j] = hb[i][j-1]; \n                }\n                if(i>0) vb[i][j] = vb[i-1][j];\n                \n                hb[i][j]+=1;\n                vb[i][j]+=1;\n                }\n            }\n        }\n        int ans = 0;\n        for(int i = 0;i<grid.size();i++)\n        {\n            for(int j = 0;j<grid[0].size();j++)\n            {\n                int size = min(hb[i][j],vb[i][j]);\n                if(size==0) continue;\n                for(int k = size;k>0;k--)\n                {\n                    if(hb[i-k+1][j]>=k && vb[i][j-k+1]>=k)\n                    {\n                        ans = max(ans,k);\n                    }\n                }\n            }\n        }\n        return ans*ans;\n    }\n};\n```
['Dynamic Programming', 'C']