二维阵列(行和列)



下面的程序(感谢Sundial)计算矩形的面积

公共类ComputeTheArea{

public static int areaOfTheRectangle (char[][] table, char ch) {
    int[] first = new int[2];
    int[] last = new int[2];
    for (int i=0; i<3; i++) { 
        for (int j=0; j<4; j++) {
               if(grid[i][j]==ch) {
                  first[0] = i;
                  first[1] = j;
               }
        }
    }
    for (int i=2; i>=0; i--) { 
        for (int j=3; j>=0; j--) { 
               if(grid[i][j]==ch) {
                  last[0] = i;
                  last[1] = j;
               }                    
        }
    }
    int answer = ((Math.max(first[0]+1,last[0]+1) - Math.min(first[0]+1,last[0]+1)) *
                  (Math.max(first[1]+1,last[1]+1) - Math.min(first[1]+1,last[1]+1)));
    return answer;
}

然而,当它运行时,它会输出错误的答案。我知道for循环有问题。我是Java新手,我需要你的帮助来修复这个方法。非常感谢!

编辑:我编辑了代码以符合Michael的回答。

首先,您不会在第一个循环中搜索矩阵中的所有元素
第二,当你找到匹配的时候,你不会崩溃
此外,这种方法也有点缺陷。例如,请参见此矩阵:

a b c b 
a _ c d 
x z b a 

在这里,您不知道在第一行停在哪个b,以获得整个b平方。

如果只在整个矩阵中循环一次,并保存最大和最小(firstlast)x和y坐标,则可以非常容易地计算面积。请参阅此代码:

public static int charArea (char[][] grid, char ch) {
    int[] first = new int[] {100, 100};
    int[] last = new int[] {-1, -1};
    for (int i=0; i<3; i++) { 
        for (int j=0; j<4; j++) {
               if(grid[i][j]==ch) {
                  first[0] = Math.min(i, first[0]);
                  first[1] = Math.min(j, first[1]);
                  last[0] = Math.max(i, last[0]);
                  last[1] = Math.max(j, last[1]);
               }
        }
    }
    int answer = (last[0] - first[0] + 1) * (last[1] - first[1] + 1);
    return answer;
}

一旦找到字符,for循环可能会中断。

循环集j=i的第一个。可能应该是j=0。

我认为长度计算不正确。两个术语都应加1。也就是说,first=0和last=3的东西的长度应该是last+1-first=4,而不是现在的3。

最新更新