1 public class Solution {
 2     public void gameOfLife(int[][] board) {
 3         if (board.length == 0 || board[0].length == 0) {
 4             return;
 5         }
 6         int[][] result = new int[board.length][board[0].length];
 7         for (int i = 0; i < board.length; i++) {
 8             for (int j = 0; j < board[0].length; j++) {
 9                 int lives = 0;
10                 for (int x = Math.max(i - 1, 0); x <= Math.min(i + 1, board.length - 1); x++) {
11                     for (int y = Math.max(j - 1, 0); y <= Math.min(j + 1, board[0].length - 1); y++) {
12                         lives += board[x][y];
13                     }
14                 }
15                 lives -= board[i][j];
16                 if (board[i][j] == 1 && lives >= 2 && lives <= 3 ||
17                 board[i][j] == 0 && lives == 3) {
18                    result[i][j] = 1;
19                 }
20             }
21         }
22         
23         for (int i = 0; i < board.length; i++) {
24             for (int j = 0; j < board[0].length; j++) {
25                 board[i][j] = result[i][j];
26             }
27         }
28     }
29 }

This is straight forward solution.

 

 1 public class Solution {
 2     public void gameOfLife(int[][] board) {
 3         if (board.length == 0 || board[0].length == 0) {
 4             return;
 5         }
 6         for (int i = 0; i < board.length; i++) {
 7             for (int j = 0; j < board[0].length; j++) {
 8                 int lives = 0;
 9                 for (int x = Math.max(0, i - 1); x <= Math.min(i + 1, board.length - 1); x++) {
10                     for (int y = Math.max(0, j - 1); y <= Math.min(j + 1, board[0].length - 1); y++) {
11                         lives += board[x][y] & 1;
12                     }
13                 }
14                 lives -= board[i][j] & 1;
15                 
16                 if (board[i][j] == 1 && lives >= 2 && lives <= 3) {
17                     board[i][j] = 3;
18                 }
19                 if (board[i][j] == 0 && lives == 3) {
20                     board[i][j] = 2;
21                 }
22             }
23         }
24         for (int i = 0; i < board.length; i++) {
25             for (int j = 0; j < board[0].length; j++) {
26                 board[i][j] >>= 1;
27             }
28         }
29     }
30 }

00 D <- D

10 L <- D

11 L <- L

01 D <- D

 

So we need to differentiate 11 = 3 and 10 = 2

 

posted on 2016-07-06 14:19  keepshuatishuati  阅读(156)  评论(0编辑  收藏  举报