用于验证二维阵列中的所有“1”构建矩形的算法

时间:2016-06-20 09:37:24

标签: java arrays algorithm

  

定义一个方法,给定一个二维整数数组,验证所有元素等于1构建一个矩形。

An Image so you can understand better

这是我到现在想出来的:

public static boolean oneRectangle(int [][] a) {
    boolean rectangle=true;
    int[][] res;
    int OneinRow=0; //keeps track of how many ones there are in the row
    int OneinColoumn=0; //keeps track of how many ones there are in a coloumn

    for(int i=0; i<a.length; i++) {
        for (int j = 0; j < a[0].length; j++) {
            while (a[i][j] == 1) {
                i++;
                OneinRow++;
            }
            while (a[i][j] == 1) {
                j++;
                OneinColoumn++;
            }
        }
    }
    res = new int[OneinRow][OneinColoumn];

    for(int k=0; k<res.length; k++)
        for(int l=0; l<res[0].length; l++)
            if(res[k][l] != 1)
                rectangle = false;

    return rectangle;
}

它没有按预期工作,因为

f = new int[][] {
            {1,2,3,4}, //1 in position 0
            {2,1,4,5}, //1 in position 1
            {3,4,5,6}};

返回true而不是false

如何修复和改进算法?

1 个答案:

答案 0 :(得分:6)

计算每行和每列的1是不够的。

我是这样做的:

遍历整个数组并跟踪发生1的每个维度中的最高和最低索引。另外计算所见的所有1个。

最后,1的数量必须与每个维度的最高和最低指数差异的乘积相同。

对于2D数组:

int minx=Integer.MAX_VALUE;
int maxx=-1;
int miny=Integer.MAX_VALUE;
int maxy=-1;
int count=0;
for x=0...
  for y=0...
    if(1==a[x][y]{
      minx=Math.min(minx,x);
      maxx=Math.max(maxx,x);
      miny=Math.min(miny,y);
      maxy=Math.max(maxy,y);
      count ++;
    }

return count==(maxx-minx+1)*(maxy-miny+1);

P.S。如果至少有一个1,您可能需要添加一个检查。