289. Game of Life

    /*
     * 289. Game of Life 
     * 2016-7-1 by Mingyang 
     * 这个题目的要求是in place,所以不能用另外一个matrix来表式,并且你改变的时候不能把下一个状态影响了
     * 所以这里用01来表示的话0可以变为3,1可以变为2
     * 然后记住这种找自己所在的九宫格,最好的方法就是设一个direction array,这样我们就可以找到
     * 然后再迭代整个array,把所有的数据拿到
     */
    int[][] dir = { { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, -1 }, { 0, 1 },
            { -1, -1 }, { -1, 0 }, { -1, 1 } };
    public void gameOfLife(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                int live = 0;
                for (int[] d : dir) {
                    if (d[0] + i < 0 || d[0] + i >= board.length
                            || d[1] + j < 0 || d[1] + j >= board[0].length)
                        continue;
                    if (board[d[0] + i][d[1] + j] == 1
                            || board[d[0] + i][d[1] + j] == 2)
                        live++;
                }
                if (board[i][j] == 0 && live == 3)
                    board[i][j] = 3;
                if (board[i][j] == 1 && (live < 2 || live > 3))
                    board[i][j] = 2;
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] %= 2;
            }
        }
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5635014.html