C# easy to understand with clear variables/comments, beats 100%


  • 0
    W

    My solution works on the concept of adding 10 to all surrounding neighbors and based on the ruleset, the next generation only survives if the sum at an individual node is inclusive between 21 and 31. Checking if a node is alive in current generation is done by using mod 2.

    public void GameOfLife(int[,] board) {
        var rows = board.GetLength(0);
        var cols = board.GetLength(1);
        // Add 10 to all neighbors if alive
        for(int y=0;y<rows;y++) {
            for(int x=0;x<cols;x++) {
                if(board[y,x]%2==1) addValEightWays(x,y,board,10);
            }
        }
        // Survives to next generation if 21 <= val <= 31
        for(int y=0;y<rows;y++) {
            for(int x=0;x<cols;x++) {
                if(board[y,x]>20 && board[y,x]<32) board[y,x]=1;
                else board[y,x]=0;
            }
        }
    }
    // adds val to all neighbors, excluding itself
    private void addValEightWays(int iX, int iY, int[,] board, int val) {
        var yStart = Math.Max(0,iY-1);
        var xStart = Math.Max(0,iX-1);
        var yEnd = Math.Min(iY+2,board.GetLength(0));
        var xEnd = Math.Min(iX+2,board.GetLength(1));
        for(int y=yStart;y<yEnd;y++) {
            for(int x=xStart;x<xEnd;x++) {
                board[y,x] += val;
            }
        }
        board[iY,iX] -= val;
    }
    

Log in to reply
 

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