|
| 1 | +""" |
| 2 | +As the desscription: |
| 3 | +You cannot update some cells first and then use their updated values to update other cells. |
| 4 | +
|
| 5 | +If we wanted to change the state in place, |
| 6 | +We need to set another number that can represent the state now and the next state |
| 7 | +So we don't mess up our count. |
| 8 | +
|
| 9 | +So I use |
| 10 | +3 means alive now and going to die, |
| 11 | +2 means dead now and going alive. |
| 12 | +
|
| 13 | +All the '%2' in the count_alive() is just a way to make it cleaner [0] |
| 14 | +Avoiding bunch of if-else |
| 15 | +Because 3%2==1 and 2%2==0 |
| 16 | +
|
| 17 | +Time Complexity is O(MN) |
| 18 | +Because we go through the whole board once [1] |
| 19 | +Each time at a (i,j) we use O(1) to count its alive neighbor [2] |
| 20 | +And go through the whole board another time to convert 3->0 and 2->1 [3] |
| 21 | +O(MN*1+MN)~=O(MN) |
| 22 | +
|
| 23 | +Space Complexity is O(1) |
| 24 | +Because we done it in place. |
| 25 | +
|
| 26 | +I learn this really nice and clean solution from @zhuyinghua1203 |
| 27 | +""" |
| 28 | +class Solution(object): |
| 29 | + def gameOfLife(self, board): |
| 30 | + if board==None or len(board)==0 or len(board[0])==0: return board |
| 31 | + |
| 32 | + m = len(board) |
| 33 | + n = len(board[0]) |
| 34 | + |
| 35 | + def count_alive(i, j): |
| 36 | + if i<0 or j<0 or i>=m or j>=n: return 0 |
| 37 | + count = 0 |
| 38 | + |
| 39 | + #bottom, top, right, left |
| 40 | + if i+1<m: count+=board[i+1][j]%2 #[0] |
| 41 | + if 0<=i-1: count+=board[i-1][j]%2 |
| 42 | + if j+1<n: count+=board[i][j+1]%2 |
| 43 | + if 0<=j-1: count+=board[i][j-1]%2 |
| 44 | + |
| 45 | + #bottomright, topleft, bottomleft, topright |
| 46 | + if i+1<m and j+1<n: count+=board[i+1][j+1]%2 |
| 47 | + if 0<=i-1 and 0<=j-1: count+=board[i-1][j-1]%2 |
| 48 | + if i+1<m and 0<=j-1: count+=board[i+1][j-1]%2 |
| 49 | + if 0<=i-1 and j+1<n: count+=board[i-1][j+1]%2 |
| 50 | + |
| 51 | + return count |
| 52 | + |
| 53 | + for i in xrange(m): #[1] |
| 54 | + for j in xrange(n): |
| 55 | + count = count_alive(i, j) #[2] |
| 56 | + |
| 57 | + if board[i][j]==1: |
| 58 | + if count<2 or count>3: |
| 59 | + board[i][j] = 3 |
| 60 | + elif board[i][j]==0: |
| 61 | + if count==3: |
| 62 | + board[i][j] = 2 |
| 63 | + |
| 64 | + for i in xrange(m): #[3] |
| 65 | + for j in xrange(n): |
| 66 | + if board[i][j]==2: |
| 67 | + board[i][j] = 1 |
| 68 | + elif board[i][j]==3: |
| 69 | + board[i][j] = 0 |
| 70 | + |
| 71 | + return board |
0 commit comments