【问题标题】:Algorithm to verify that all the "1" in a two-dimensional Array build a rectangle验证二维数组中所有“1”构建矩形的算法
【发布时间】:2016-06-20 09:37:23
【问题描述】:

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

这是我到现在为止的想法:

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

如何修复和改进算法?

【问题讨论】:

  • 注意,res 表在创建后只包含零,您不要用其他任何内容填充它
  • 试着解释一下你自己(和我们)你试图实现的算法。
  • @krzydyn 谢谢,确实 res 数组中没有任何内容,我会修复它
  • 你的算法不正确,连你的代码都乱写了。您正在计算列中 1 的数量,但在哪一列??
  • @Prince 这也是真的……我可能不得不想出一个完全不同的算法

标签: java arrays algorithm


【解决方案1】:

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

我是这样做的:

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

最后1的个数必须与每个维度的最高和最低索引之差的乘积相同。

对于二维数组:

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);

附:如果至少有一个 1,您可能需要添加检查。

【讨论】:

  • 如果你愿意保持更复杂的状态,也可以一次性完成。
  • @Sorin:一次性完成。查看我添加的伪代码。
  • @MrSmith42 你能解释一下Integer.MAX_VALUE 的工作原理吗?我以前从未使用过。
  • Integer.MAX_VALUE 等于 2,147,483,648
  • 因为第一次,minx = y;因为无论 y 的值是多少,它都不会大于 MAX_VALUE
猜你喜欢
  • 2021-06-26
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 2012-01-09
  • 2012-07-04
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多