java - 验证二维Array中的所有 "1"是否构成矩形的算法

标签 java arrays algorithm

Define a method that, given a two-dimensional Array of Integers, verifies that all the elements equals to 1 build a rectangle.

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 是不够的。

我是这样做的:

遍历整个数组并跟踪每个维度中出现 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,您可能想要添加一张支票。

关于java - 验证二维Array中的所有 "1"是否构成矩形的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37919144/

相关文章:

c++ - C++遍历一般树

java - 如何将白色背景更改为黑色

java - 如何从不同的文件加载基于 spring-boot 的 REST 应用程序属性?

c# - 将字符串数组排序为 Int

ruby - 在Ruby中查找数组中两个数字的每个组合的总和

algorithm - 什么是没有。具有 n 个标记节点的不同二叉树的可能性?

java - 在 ClientRequestFilter 中动态设置 ClientRequestContext 属性

java - PorterduffXfermode : Clear a section of a bitmap

java - 无法使用 HibernateOGM 连接到 Mongodb

java - 如何从匿名类中获取不同类型的数据