C# solution: live->dead:2, dead->live:3


  • 0
    B
    public class Solution 
    {
        // dead         0
        // live         1
        // live->dead   2
        // dead->live   3
        public void GameOfLife(int[,] board) 
        {
            var directions = new Tuple<int,int>[] { Tuple.Create(-1,-1), Tuple.Create(0,-1), Tuple.Create(1,-1), Tuple.Create(-1,0),
                                                    Tuple.Create(1,0), Tuple.Create(-1,1), Tuple.Create(0,1), Tuple.Create(1,1)};
    
            var row = board.GetLength(0);
            var col = board.GetLength(1);
    
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    var liveCount = 0;
    
                    foreach(var direction in directions)
                    {
                        var surroundX = i + direction.Item1;
                        var surroundY = j + direction.Item2;
    
                        if (surroundX < 0 || surroundX >= row || surroundY < 0 || surroundY >= col) continue;
                        
                        if (board[surroundX, surroundY] == 1 || board[surroundX, surroundY] == 2) liveCount++;
                    }
    
                    if      (board[i, j] % 2 == 1 && liveCount < 2)  board[i, j] = 2;
                    else if (board[i, j] % 2 == 1 && liveCount > 3)  board[i, j] = 2;
                    else if (board[i, j] % 2 == 0 && liveCount == 3) board[i, j] = 3;
                }
            }
    
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    board[i,j] %= 2;
                }
            }
    
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.