Game of Life LEETCODE中档算法题JAVA实现

来源:互联网 发布:unicode to utf8 java 编辑:程序博客网 时间:2024/04/29 14:43

在LEETCODE上做这道题https://leetcode.com/problems/game-of-life/ 

在DISCUSS讨论中看到了惊为天人的答案,不需要额外的空间,巧妙利用二进制,教科书般值得背诵的数组边界控制。

 用二进制储存状态,0代表死,1代表活,第二位代表下一代的死活状态,第一位代表当代的死活状态

 00 代表下一代死 当代死 

01代表下一代死 当代活 

10代表下一代活,当代死 

11代表下一代活,这一代活 

这样做的好处是不用额外的空间来储存和更新数据,直接对原二进制操作,board[i][j] & 1就可以获得当代状态 

a&b中的&是二目操作符,先把a,b转换成二进制,然后对每一位考虑,若都为1,则为1,否则为0

具体看上面的四个数据,00 & 1 ,结果是0,当代死;01&1 ,结果是1,当代活;10&1,结果实11&1,结果是01,当代活; 

为得到下一代数据,我们用 board[i][j] >>1 来忽略第一位,直接得到下一代数据。


</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
</pre><pre name="code" class="java">public void gameOfLife(int[][] board) {    if(board == null || board.length == 0) return;    int m = board.length, n = board[0].length;    for(int i = 0; i < m; i++) {        for(int j = 0; j < n; j++) {            int lives = liveNeighbors(board, m, n, i, j);            // In the beginning, every 2nd bit is 0;            // So we only need to care about when 2nd bit will become 1.            if((board[i][j] & 1) == 1 && (lives >= 2 && lives <= 3)) {                board[i][j] = 3; // Make the 2nd bit 1: 01 ---> 11            }            if((board[i][j] & 1) == 0 && lives == 3) {                board[i][j] = 2; // Make the 2nd bit 1: 00 ---> 10            }        }    }    for(int i = 0; i < m; i++) {        for(int j = 0; j < n; j++) {            board[i][j] >>= 1;  // Get the 2nd state.        }    }}public int liveNeighbors(int[][] board, int m, int n, int i, int j) {    int lives = 0;    for(int p = Math.max(i - 1, 0); p <= Math.min(i + 1, m - 1); p++) {        for(int q = Math.max(j - 1, 0); q <= Math.min(j + 1, n - 1); q++) {            lives += board[p][q] & 1;        }    }    lives -= board[i][j] & 1;    return lives;}


0 0
原创粉丝点击