[英]Count cell in an island with flood fill algorithm
我有一個 Matrix[x][y] 的整數,在 C# 中為 1 或 0。 我需要計算一個島上有多少個 0,我正在考慮使用洪水填充算法,但我不知道如何編寫它。 有任何想法嗎?
這就是我所做的
void FloodFill(int r, int c)
{
player = FindObjectOfType<Player>();
r = Mathf.RoundToInt(player.coords.x);
c = Mathf.RoundToInt(player.coords.y);
if (matrix[r][c] == 1)
{
count++;
FloodFill(r + 1 , c);
FloodFill(r , c + 1);
FloodFill(r - 1 , c);
FloodFill(r , c - 1);
}
}
我不認為是正確的。
我會給你算法,把編碼留給練習。
首先創建另一個名為visited[x][y]
布爾矩陣
逐行循環遍歷原始矩陣,每當您看到 1 時,您首先會使用我們上面創建的矩陣檢查它是否已經被訪問過。
如果(a, b)
沒有被訪問,那么你從 (a, b) 開始在所有為 1 的鄰居點上執行DFS
或BFS
。在你這樣做的同時也標記了visited[a][b] = true
。
完成(a, b)
的DFS/BFS
, (a, b)
島數增加 1 並移至(a + 1, b)
。
您將在訪問(x, y)
后獲得總數
總運行時間: O(xy)
我寫了這個,離我有多遠?
void FloodFill()
{
player = FindObjectOfType<Player>();
r = Mathf.RoundToInt(player.coords.x);
c = Mathf.RoundToInt(player.coords.y);
Stack cells = new Stack();
Stack visited = new Stack();
cells.Push(matrix[r][c]);
while (cells.Count > 0)
{
matrix[r][c] = cells.Pop(); //error cannot convert "object" to "int"
if (matrix[r][c] == 0)
{
visited.Push(matrix[r][c]);
cells.Push(matrix[r + 1][c]);
cells.Push(matrix[r][c + 1]);
cells.Push(matrix[r - 1][c]);
cells.Push(matrix[r][c - 1]);
}
}
visited.Count(); //error "Stack.Count" cannot be used as a method
return;
}
我知道我缺少一些東西來檢查單元格是否已被訪問過,並且存在我不知道如何解決的錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.