参考了题解:
public class Solution {
public int Largest1BorderedSquare(int[][] grid) {
int maxLen = 0;
if(grid.Length == 0 || grid[0].Length == 0)
return 0;
int h = grid.Length;
int w = grid[0].Length;
bool flag = true;
for(int i = 0; i < h; i++)
{
for(int j = 0; j < w; j++)
{
if(grid[i][j] == 1)
{
//默认为边长为1的正方形
int preLen = 1;
//保证边长从当前记录的最长边+1算起,避免不必要的计算
int curLen = (preLen > maxLen ? preLen + 1: maxLen +1);
//除当前节点外的边的长度
int extLen = curLen - 1;
//以当前节点为左上顶点,边长为curLen,直到遇到边界为止
while(extLen + j < w && extLen + i < h)
{
flag = true;
//遍历上边和左边是否存在0
for(int k = 1; k <= extLen; k++)
{
if(grid[i+k][j] != 1)
{
flag = false;
break;
}
if(grid[i][j+k] != 1)
{
flag = false;
break;
}
}
//如果存在0,即边不存在,跳出当前节点
if(!flag)
break;
//遍历下边和右边的元素
for(int k = 1; k <= extLen; k++)
{
if(grid[i+extLen][j+k] != 1)
{
flag = false;
break;
}
if(grid[i+ k][j+extLen] != 1)
{
flag = false;
break;
}
}
//如果下边和右边也不存在0,正方形成立,记录下当前边长
if(flag)
{
Console.WriteLine(i+"=="+j+"=="+curLen+"==="+preLen+"=="+extLen);
preLen = curLen;
}
curLen++;
extLen++;
}
maxLen = (maxLen > preLen ? maxLen : preLen);
}
}
}
return maxLen * maxLen;
}
}