Saturday, November 21, 2015

[leetcode]Game of life

用bit去记current和future
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Solution {
    public void gameOfLife(int[][] board) {
        for (int i = 0; i < board.length; i++){
            for (int j = 0; j < board[i].length; j++){
                board[i][j] |= (nextState(board, i, j) << 1);
            }
        }
        for (int i = 0; i < board.length; i++){
            for (int j = 0; j < board[i].length; j++){
                board[i][j] = futureBit(board[i][j]);
            }
        }
    }
    
    private int nextState(int [][]board, int i, int j){
        int live = currentBit(board[i][j]);
        int up    = i == 0?0:currentBit(board[i-1][j]);
        int down  = i == board.length-1?0:currentBit(board[i+1][j]); 
        int left  = j == 0?0:currentBit(board[i][j-1]);
        int right = j == board[i].length-1?0:currentBit(board[i][j+1]);
        int upLeft = (i==0 || j==0)?0:currentBit(board[i-1][j-1]);
        int upRight = (i == 0||j==board[i].length-1)?0:currentBit(board[i-1][j+1]);
        int downLeft = (i == board.length-1||j==0)?0:currentBit(board[i+1][j-1]);
        int downRight = (i == board.length-1||j==board[i].length-1)?0:currentBit(board[i+1][j+1]);
        int totalLive = up+down+left+right+upLeft+upRight+downLeft+downRight;
        if (live == 1){
            if (totalLive < 2) return 0;
            if (totalLive > 3) return 0;
            return 1;
        }
        return totalLive == 3?1:0;
    }
    
    
    
    private int futureBit(int num){
        return (num&0x2) >> 1;
    }
    
    private int currentBit(int num){
        return (num&0x1);
    }
    
}

No comments:

Post a Comment