0

任务:我需要创建一个方法,从可能是正方形但不需要的矩阵(二维数组)中找到最大的正方形子矩阵,边界为 1,内部为0 。矩阵的所有元素都是 1 和 0。

这是我的代码

static void sub(int[][] p){
    int sm=(p[0].length<p.length)?p[0].length:p.length;
    int bg=(p[0].length<p.length)?p.length:p[0].length;
    if(p.length==p[0].length){
        sm=p.length;bg=p.length;
    }
    int t=0;
    boolean cool=false;

    z:for(int z=sm;z>2;z--){
        x:for(int x=0,l=0;x<sm-z;x++,l++){
            y:for(int y=0,m=0;y<bg-z;y++,m++){
                for (int i=y;i<=z+m;i++){
                    if(p[x][i]!=1){cool=false; continue x;}
                    else cool=true;
                    if(p[z][i]!=1){cool=false; continue x;}
                    else cool=true;
                }
                int n=0;
                for(int j=0;j<z-1;j++)
                for(int i=y+1;i<z+m;i++){
                    if(p[x+n][i]!=0){cool=false; continue x;}
                    else cool=true;
                    if(i==z+m-1)n++;
                }
                for (int i=x+1;i<z+l;i++){
                    if(p[i][y]!=1){cool=false; continue x;}
                    else cool=true;
                }
                for(int i=x+1;i<=z-1;i++){
                    if(p[i][z+t]!=1) continue x;
                }
                if(cool){
                    System.out.println(x+" "+y+" "+z);
                }
                t++;
            }
            t=0;
        }
    }
}
public static void main(String[] args) {
    int[][] p = {
            {1,1,1,1,1,1,1,1,1},
            {1,0,0,0,1,1,1,1,1},
            {1,0,0,0,1,1,1,1,1},
            {1,0,0,0,1,1,1,1,1},
            {1,0,0,0,1,1,1,1,1},
            {1,0,0,0,1,1,1,1,1},
            {1,1,1,1,1,1,1,1,1}
    };
    sub(p);
}

变量: x 和 y - 起始 x 和 y 坐标 (p[x][y]) z - 方形子矩阵的长度

哪里错了。为什么我在这个例子中没有得到那些 x、y 和 z。我已经测试了所有这些 for 循环,它们采用了应有的元素。如果你有一些建议,我想知道一些更好的方法。谢谢!

4

1 回答 1

0

我不能真正理解你的方法,但我认为它可能有点过头了。例如,当可以在一个地方完成时,您有几段代码检查一个元素是 0 还是 1。

它可能会帮助您退后一步并重新评估您的代码。它应该做什么?

“我需要制定一种方法来找到最大的方形子矩阵,其中边界为 1,内部为 0”,例如:

    {1,1,1,1,1,1,1,1,1},
    {1,0,0,0,1,1,1,1,1},
    {1,0,0,0,1,1,1,1,1},
    {1,0,0,0,1,1,1,1,1},
    {1,0,0,0,1,1,1,1,1},
    {1,0,0,0,1,1,1,1,1},
    {1,1,1,1,1,1,1,1,1}

现在我想我可以得到你的方法,但让我们把它写出来:

最大平方 = 0

对于矩阵中的每个元素:

如果是正方形的角

找出广场有多大

将最大平方设置为最大(平方,最大平方)

万一

结束

返回最大平方

现在的问题是如何找出正方形的大小。为此,我们可以从单个零开始,然后检查正方形的下一层是否存在。像这样:

{0} 检查下一层

{0 0} ,

{0 0} 检查下一层

{0 0 0}

{0 0 0}

{0 0 0} 检查下一层

等等

为此,我们可以:

while matrix[i][j]==0:
    //check row below bottom of square
    for j =start_j to i:
        if matrix[i][j]!=0:
            break
        i++

    // if the side is short than the current side length
    if i<j:
        break

    //check column to right of square
    for j= start_j to i:
        if matrix[i][j]!=0:
            break
        j++
    //the row below and column to the right have all 0's so add to the square
    biggest_square++

关于样式的最后一点说明:通常最好将内容分开并将块的开头和结尾放在新行上,并为变量选择描述性名称。我不知道变量 sm 和 bg 是什么意思,而且“酷”并不是特别具有描述性。

抱歉有任何错误,我希望这可以帮助您解决问题。

于 2016-01-15T13:12:26.293 回答