Python DP with explanation, faster than 90%  runtime and less than 100% space.
construct dp matrix, each element dp[i][j] is a tuple that stores the length of consecutive 1s ending with grid[i][j] in horizontal and vertical directions. \n2
1. construct dp matrix, each element dp[i][j] is a tuple that stores the length of consecutive 1s ending with grid[i][j] in horizontal and vertical directions. \n2. res stores the length of the longest subgrids with all 1 edges.\n3. at dp[i][j], if dp[i][j]>res, we check the subgrids with edge length ranging from res+1 to min(dp[i][j]). for edge length of L, we just need to check information stored in dp[i][j-L+1] and dp[i-L+1][j]. update res if we find a larger subgrids.\n4. return res squared.\n\n```\nclass Solution:\n    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n        r,c = len(grid),len(grid[0])\n        \n        dp = [[(0,0) for j in range(c)] for i in range(r)]\n        \n        if grid[0][0]==1:\n            dp[0][0]=(1,1)\n        \n            \n        res = 0\n        \n        for i in range(r):\n            for j in range(c):\n                if grid[i][j]==1:\n                    dp[i][j] = (dp[i][max(j-1,0)][0]+1,dp[max(i-1,0)][j][1]+1)\n                else:\n                    dp[i][j] = (0,0)\n                \n                if dp[i][j][0]>res and dp[i][j][1]>res:\n                    l = res + 1\n                    if l!=1:\n                        while(l<=dp[i][j][0] and l<=dp[i][j][1]):\n                            if dp[i][j-l+1][1]>=l and dp[i-l+1][j][0]>=l:\n                                \n                                res = l\n\n                            l+=1\n                    else:\n                        res = 1\n       \n        return res**2\n                    \n            \n        \n```
[]