C++ O(n ^ 3)
Accumulate the number of consecutive horizontal and vertical 1s in two helper grids.\n\nThen, starting from the maximum possible square size sz_s, check the len
Accumulate the number of consecutive horizontal and vertical ```1```s in two helper grids.\n\nThen, starting from the maximum possible square size ```sz_s```, check the length of 4 sides using the helper grids.\n```\nint largest1BorderedSquare(vector<vector<int>>& grid) {\n  auto sz_x = grid.size(), sz_y = grid[0].size();\n  vector<vector<int>> sx(sz_x, vector<int>(sz_y)), sy(sz_x, vector<int>(sz_y));\n  for (auto x = 0; x < sz_x; ++x)\n    for (auto y = 0; y < sz_y; ++y)\n      if (grid[x][y] == 0) sx[x][y] = sy[x][y] = 0;\n      else {\n        sx[x][y] = 1 + (y == 0 ? 0 : sx[x][y - 1]);\n        sy[x][y] = 1 + (x == 0 ? 0 : sy[x - 1][y]);\n      }\n  for (int sz_s = min(sz_y, sz_x) - 1; sz_s >= 0; --sz_s)\n    for (auto x = 0; x + sz_s < sz_x; ++x)\n      for (auto y = 0; y + sz_s < sz_y; ++y) {\n        if (sx[x][y + sz_s] > sz_s && sx[x + sz_s][y + sz_s] > sz_s &&\n          sy[x + sz_s][y] > sz_s && sy[x + sz_s][y + sz_s] > sz_s) return (sz_s + 1) * (sz_s + 1);\n      }\n  return 0;\n}\n```
[]