私は、壁で囲まれた空白の数を数えるフラッドフィルアルゴリズムを作成しようとしています。 2Dの文字列配列を使用しています。壁は「1」で表され、空白は空白です。 理想的には、アルゴリズムは、配列内のすべてのStringをチェックし、map [x] [y]のStringがnullでない任意のポイントを返し、壁で囲まれた空白の数を数えます。 しかし、分時には部屋数が非常に長くなり、どこが間違っているのかわかりません。部屋数をカウントするフラッドフィルアルゴリズム
public static void floodFill(int x, int y, String oldChar, String newChar){
x = 0;
y=0;
if (x < 0 || y < 0 || x > map.length || y > map[0].length){
return;
}
if (map[x][y] != oldChar){
return;
}
map[x][y] = newChar;
// Recursive calls
floodFill(x - 1, y, oldChar, newChar);
floodFill(x +1, y, oldChar, newChar);
floodFill(x, y-1, oldChar, newChar);
floodFill(x, y+1, oldChar, newChar);
}
public static void getNumOfRooms(String map[][]){
roomCount = -1;
for(x = 0; x < map.length; x++){
for (y = 0; y < map[0].length; y++){
if (map[x][y] == null){
floodFill(x, y, null, "x");
roomCount+=1;
System.out.println(map);
}
}
}
なぜfloodFill()の先頭にxとyを0に設定していますか? – Barry
floodFillパラメータは(x + 1、y)、(x-1、y)、(x、y + 1)、(x、y-1)ではないでしょうか?あなたは疑わしいcoord pairingsを持っています。また、roomCountは0から始めるべきではありませんか? – Barry
xとyを0に設定しなかった場合、配列外のエラーが発生します。基本的には、[0,0]から始まる配列全体を検索します。はい、ペアリングが修正されます。 roomCountは-1になります。なぜなら、外側の領域も1つの空白として数えるからです。 –