Skip to content

Commit f7306ce

Browse files
committed
♻️ (mine-sweeper): refactor reveal with visited queue
1 parent c28b25b commit f7306ce

File tree

1 file changed

+42
-27
lines changed

1 file changed

+42
-27
lines changed

internal/game/game.go

Lines changed: 42 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -173,36 +173,51 @@ func (board *Board) ToggleFlag(row, col int) {
173173

174174
// Reveal - 從 row, col 開始翻開周圍不是地雷,直到遇到非零的格子
175175
func (board *Board) Reveal(row, col int) {
176-
// 超出邊界
177-
if row < 0 || row >= board.rows ||
178-
col < 0 || col >= board.cols {
179-
return
180-
}
181-
182-
cell := board.cells[row][col]
183-
// 已經被揭開
184-
if cell.Revealed {
185-
return
186-
}
176+
visitQueue := []coord{{
177+
Row: row,
178+
Col: col,
179+
}}
180+
// 透過 queue 來實做 BFS
181+
for len(visitQueue) > 0 {
182+
// pop up first
183+
cellCoord := visitQueue[0]
184+
visitQueue = visitQueue[1:]
185+
curRow, curCol := cellCoord.Row, cellCoord.Col
186+
187+
// 超出邊界
188+
if curRow < 0 || curRow >= board.rows ||
189+
curCol < 0 || curCol >= board.cols {
190+
continue
191+
}
187192

188-
// 標注該格已經被揭開
189-
board.cells[row][col].Revealed = true
190-
if cell.Flagged {
191-
board.RemainingFlags++
192-
board.cells[row][col].Flagged = false
193-
}
193+
cell := board.cells[curRow][curCol]
194+
// 已經被揭開
195+
if cell.Revealed {
196+
continue
197+
}
194198

195-
// 如果是空白格 (AdjacenetMines = 0, 且不是地雷)
196-
if !cell.IsMine && cell.AdjacenetMines == 0 {
197-
// 鄰近所有方向
198-
neighborDirections := [8]coord{
199-
{Row: -1, Col: -1}, {Row: -1, Col: 0}, {Row: -1, Col: 1},
200-
{Row: 0, Col: -1}, {Row: 0, Col: 1},
201-
{Row: 1, Col: -1}, {Row: 1, Col: 0}, {Row: 1, Col: 1},
199+
// 標注該格已經被揭開
200+
board.cells[curRow][curCol].Revealed = true
201+
if cell.Flagged {
202+
board.RemainingFlags++
203+
board.cells[curRow][curCol].Flagged = false
202204
}
203-
for _, direction := range neighborDirections {
204-
neighborRow, neighborCol := row+direction.Row, col+direction.Col
205-
board.Reveal(neighborRow, neighborCol)
205+
206+
// 如果是空白格 (AdjacenetMines = 0, 且不是地雷)
207+
if !cell.IsMine && cell.AdjacenetMines == 0 {
208+
// 鄰近所有方向
209+
neighborDirections := [8]coord{
210+
{Row: -1, Col: -1}, {Row: -1, Col: 0}, {Row: -1, Col: 1},
211+
{Row: 0, Col: -1}, {Row: 0, Col: 1},
212+
{Row: 1, Col: -1}, {Row: 1, Col: 0}, {Row: 1, Col: 1},
213+
}
214+
for _, direction := range neighborDirections {
215+
neighborRow, neighborCol := curRow+direction.Row, curCol+direction.Col
216+
visitQueue = append(visitQueue, coord{
217+
Row: neighborRow,
218+
Col: neighborCol,
219+
})
220+
}
206221
}
207222
}
208223
}

0 commit comments

Comments
 (0)