下面的程序(感谢日d)计算矩形的面积
公共类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的新手,我需要您的帮助来解决此方法。请,非常感谢你!
编辑:我编辑代码以符合迈克尔的答案。
最佳答案
首先,您不会在第一个循环中搜索矩阵中的所有元素。
其次,当您找到比赛时,您不会中断。
而且,这种方法有点缺陷。例如,请参见以下矩阵:
a b c b
a _ c d
x z b a
在这里,您将不知道在第一行停在哪个
b
位置以获得整个b
平方。相反,如果只循环遍历整个矩阵一次并保存最大和最小(
first
和last
)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;
}