Java in place solution


  • 0
    S
    public class Solution {
    public void gameOfLife(int[][] board) {
        
        if (board.length == 0 || board[0].length == 0)
            return;
          
        Map<Position, Integer> map = new HashMap<>();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                int countOnes = countNeighbors(board, i, j);
                if (countOnes < 2 || countOnes > 3) {
                    if (board[i][j] == 1)
                        map.put(new Position(i, j), 0);
                } else if (countOnes == 3) {
                    if (board[i][j] == 0)
                        map.put(new Position(i, j), 1);
                }
            }
        }
        
        for (Position position : map.keySet()) {
            board[position.i][position.j] = map.get(position);
        }
    }
    
    private int countNeighbors(int[][] board, int i, int j) {
        int rowStart = i - 1 >= 0 ? i - 1 : 0;
        int colStart = j - 1 >= 0 ? j - 1 : 0;
        int rowEnd = i + 1 < board.length ? i + 1 : board.length - 1;
        int colEnd = j + 1 < board[0].length ? j + 1 : board[0].length - 1;
        int sum = 0;
        for (int m = rowStart; m <= rowEnd; m++) {
            for (int n = colStart; n <= colEnd; n++) {
                if (board[m][n] == 1 && (m != i || n != j)) {
                    sum++;
                }
            }
        }
        return sum;
    }
    
    private static class Position {
        int i;
        int j;
        public Position(int i, int j) {
            this.i = i;
            this.j = j;
        }
    }
    

    }


  • 1
    J

    dude, u called using a data structure in-place??


Log in to reply
 

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