0

The program below (thanks to Sundial) computes the area of a rectangle

public class 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;
}

However, when it is run, it outputs the wrong answer. I know there is something wrong with the for loop. I'm new in Java and I need your help for me to fix the method. Please and thank you very much!

EDIT: I edited the code to conform to Michael's answer.

4

2 に答える 2

1

まず、最初のループで行列内のすべての要素を検索するわけではありません。
第二に、一致を見つけたときに中断しません。
また、このアプローチには少し欠陥があります。たとえば、次のマトリックスを参照してください。

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

ここでは、正方形b全体を取得するために最初の行で停止する必要があるかわかりません。b

代わりに、マトリックス全体を 1 回ループして、最大および最小 (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;
}
于 2012-07-15T11:38:36.010 に答える
0

forループは、文字が見つかるとおそらく壊れます。

最初のforループはj=iを設定します。代わりに、おそらくj=0になるはずです。

長さの計算が正しくないと思います。両方の用語に1を追加する必要があります。つまり、first=0およびlast=3の長さは、現在の3ではなく、last + 1-first=4である必要があります。

于 2012-07-15T11:33:02.620 に答える