Implementing Flood Fill Algorithm in Kotlin

Viewed 44
import java.util.Queue
import java.util.LinkedList

fun explore(row: Int, column: Int) {
    val length1 = minefield.size
    val length2 = minefield[0].size
    if (displayedMinefield[row][column] == "/") return
    
    val queue: Queue<Int> = LinkedList<Int>()
    queue.add(listOf(row, column))
    while (!queue.isEmpty()) {
        val (i, j) = queue.first
        queue.removeFirst()
        if (i < 0 || i >= length1 || j < 0 || j >= length2) {
            continue
        } else {
            if (checkIfMinesAround(i, j)) {
                displayedMinefield[i][j] = minefield[i][j]
            } else {
                displayedMinefield[i][j] = "/"
            }
            queue.add(listOf(i + 1, j))
            queue.add(listOf(i - 1, j))
            queue.add(listOf(i, j + 1))
            queue.add(listOf(i, j - 1))
        }
    }
}

I'm trying to implement the flood fill algorithm to recreate minesweeper. Essentially, this is how this part of the game works:

  1. There is a minefield like the following:
 │123456789│
—│—————————│
1│.........│
2│.........│
3│.........│
4│.........│
5│.........│
6│.........│
7│.........│
8│.........│
9│.........│
—│—————————│
  1. If a player chooses to explore a cell, there are 3 different possibilities: A. They explore a mine and lose (this part is easy) B. If the chosen cell is empty but there are mines around it, only the chosen cell is explored C. If there aren't any mines around it (and it's empty), the current cell should be marked with a "/." However, all the cells around it should be explored automatically as well (applying the same rules). In addition, if any of those cells are in the situation, meaning they also have no mines around them, all of their surrounding cells should be explored automatically.

So, it's a recursive process until the conditions aren't met anymore. The code above is what I have so far for the flood fill algorithm. I need help with adding to it. I already have a function that checks if there are mines around. So, I just need to perfect this function. Note: minefield is a mutable list that contains all the actual information, displayedMinefield is what is shown to the user.

0 Answers
Related