java, 3ms, easy to understand
class Solution {\n    public int largest1BorderedSquare(int[][] grid) {\n        if(grid.length == 0) return 0;\n        int m = grid.length, n = grid[0].length
class Solution {\n    public int largest1BorderedSquare(int[][] grid) {\n        if(grid.length == 0) return 0;\n        int m = grid.length, n = grid[0].length;\n        int hor[][] = new int[m][n]; \n        int ver[][] = new int[m][n];\n        for (int i = 0; i < m; i++){\n            for(int j = 0; j < n; j++){\n                if(grid[i][j] == 1){\n                    hor[i][j] = j == 0? 1 : hor[i][j-1] + 1;\n                    ver[i][j] = i == 0? 1 : ver[i-1][j] + 1;\n                }\n            }\n        }\n        int max = 0;\n        for(int i = m-1; i >= 0; i--){\n            for(int j = n-1; j >= 0; j--){\n                int edge = Math.min(hor[i][j], ver[i][j]);\n                while(edge > max){\n                    if(ver[i][j-edge+1] >= edge && hor[i-edge+1][j] >= edge) max = edge;\n                    edge--;\n                }\n            }\n        }\n        return max * max;\n    }\n}
[]