我有一個二維數組,它就像一個迷宮。 因此,我通過第一行循環查看是否有一個零(這個零是開頭),然後我下來看看是否有另一個低於零的零。如何遍歷一個數組並獲得有多少個零點
問題是,在第2行之後,我不知道如何編寫代碼來檢查零點的左邊,右邊或下邊,然後移動並繼續,直到我不能再這樣做。
import java.util.Scanner;
public class AssignmentTwo
{
//int[rows][columns]
int[][] gasCavern = {{1,1,1,1,1,0,1},
{1,0,0,1,1,0,1},
{1,1,1,0,0,0,1},
{1,1,0,0,1,1,1},
{1,0,1,0,1,0,1},
{1,0,1,0,0,0,1},
{0,0,0,1,1,1,0},
{1,1,1,0,0,0,1}};
int counter = 0;
boolean checked = false;
// forLoop that deals with the first 2 rows.
// First check 1st row for a zero.
// Then check down and increment counter which ultimately shows area.
for(int column = 0; column < gasCavern[0].length; column++)
{
//Checking for opening in 1st row
if(gasCavern[0][column]== 0)
{
counter++;
gasCavern[0][column] = 2;
if(gasCavern[1][column]==0)
{
counter++;
}
}
}
for(int i=1; i<gasCavern.length; i++)
{
for(int j=0; j < gasCavern.length; j++)
{
if(gasCavern[i][j])
{
//Looking left
if(gasCavern[i][j-1]==2)
{
gasCavern[i][j-1]=2;
counter++;
}
//Looking Right
if(gasCavern[i][j+1]==2)
{
gasCavern[i][j+1]=2;
counter++;
}
//Looking up
if(gasCavern[i+1][j]==2)
{
gasCavern[i+1][j]=2;
counter++;
}
//Looking down
if(gasCavern[i-1][j]==2)
{
gasCavern[i-1][j]==2
counter++;
}
}
}
}
public boolean checkedForZeros()
{
//If returning false,go through while loop again
}
}
這是我到目前爲止的代碼。如果我不清楚這是什麼,我想發生:
謝謝,我編輯我的代碼我現在有。我處於將所有訪問過的零變爲2的階段,所以我不再重複它們。但是,我不清楚如何從這一點繼續。我的教授建議我使用一個while循環來將我的2個forloop與條件包含在一起,但我仍然不確定。 – Anonymous
@匿名你還堅持這個嗎? – James