Leetcode - Set Matrix Zeroes
Leetcode - Pascal's Triangle II

Leetcode - Game of Life

violet posted @ Apr 06, 2020 07:12:16 AM in 算法 with tags Algorithm Golang array , 214 阅读

https://leetcode.com/problems/game-of-life/

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

 

Something I've learned can be used here.

1. How to goes different directions

2. If it requires remain previous value, how to maintain it

func gameOfLife(board [][]int)  {
    if len(board) == 0 || len(board[0]) == 0 {
        return
    }
    for i := 0; i < len(board); i++ {
        for j := 0; j < len(board[0]); j++ {
            count := liveNeighbors(board, i, j)
            if board[i][j] > 0 {
                if count < 2 {
                    board[i][j] = 2 // should be dead
                }
                if count > 3 {
                    board[i][j] = 2 // should be dead
                }
            } else if board[i][j] == 0 {
                if count == 3 {
                    board[i][j] = -1 // should be alive
                }
            }
        }
    }
    for i := 0; i < len(board); i++ {
        for j := 0; j < len(board[0]); j++ {
            if board[i][j] == 2 {
                board[i][j] = 0
            }
            if board[i][j] == -1 {
                board[i][j] = 1
            }
        }
    }
}

func liveNeighbors(board [][]int, i, j int) int {
    directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}}
    count := 0
    for _, d := range directions {
        x := i + d[0]
        y := j + d[1]
        if x >= 0 && y >= 0 && x < len(board) && y < len(board[0]) {
            if board[x][y] > 0 {  
                count++
            }
        }
    }
    return count
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter