Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

289. Game of Life

Topics: Array Matrix Simulation

Solution 1

Implementation

class Solution {
    fun gameOfLife(board: Array<IntArray>): Unit {
        val height = board.size
        val width = board[0].size
        val neighbors = Array(height) { Array<Int>(width) { 0 } }

        for (i in 0 until height) {
            for (j in 0 until width) {
                for (ni in (i-1)..(i+1)) {
                    if (ni < 0 || ni >= height) continue
                    for (nj in (j-1)..(j+1)) {
                        if (nj < 0 || nj >= width) continue
                        if (ni == i && nj == j) continue
                        neighbors[i][j] += board[ni][nj]
                    }
                }
            }
        }

        for (i in 0 until height) {
            for (j in 0 until width) {
                val live = neighbors[i][j] == 3 || (neighbors[i][j] == 2 && board[i][j] == 1)
                board[i][j] = if (live) 1 else 0
            }
        }
    }
}

Solution 2

Implementation

class Solution {
    fun gameOfLife(board: Array<IntArray>): Unit {
        val height = board.size
        val width = board[0].size

        for (i in 0 until height) {
            for (j in 0 until width) {
                var neighbors = 0
                for (ni in (i-1)..(i+1)) {
                    if (ni < 0 || ni >= height) continue
                    for (nj in (j-1)..(j+1)) {
                        if (nj < 0 || nj >= width) continue
                        if (ni == i && nj == j) continue
                        neighbors += board[ni][nj] % 10
                    }
                }
                board[i][j] += neighbors * 10
            }
        }

        for (i in 0 until height) {
            for (j in 0 until width) {
                val live = board[i][j] / 10 == 3 || (board[i][j] / 10 == 2 && board[i][j] % 10 == 1)
                board[i][j] = if (live) 1 else 0
            }
        }
    }
}