思路: 因为要求是in-place。所以不能用额外的空间。我的做法是:遍历矩阵,每碰到一个数字,判断是否需要转变。如果需要转变的话,我们把这个数字减2的值代替原来的数字。例如:如果当前数字是1,并且经过判断需要改变,那我们就把-1代替1写进当前元素。又如果当前数字是0,并且经过判断需要改变,我们把-2代替0写进当前元素。上述操作完成后,再遍历一遍数组,碰到-1,改成0;碰到-2改成1。这样就好了。下面展示代码:
class Solution {
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int number = board[i][j];
if(check(board,i,j)) number = number - 2; board[i][j] = number;
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int number = board[i][j];
if(number == - 1) board[i][j] = 0;
if(number == - 2) board[i][j] = 1;
}
}
}
// 判断是否需要改变函数
private boolean check(int[][] board, int i, int j){
int m = board.length;
int n = board[0].length;
if(board[i][j] == 0){
int count = 0;
if(i >= 0 && i < m && j >= 1 && j < n + 1 && (board[i][j - 1] == 1 || board[i][j - 1] == - 1)) count++;
if(i >= 0 && i < m && j >= -1 && j < n - 1 && (board[i][j + 1] == 1 || board[i][j + 1] == - 1)) count++;
if(i >= -1 && i < m - 1 && j >= 0 && j < n && (board[i + 1][j] == 1 || board[i + 1][j] == - 1)) count++;
if(i >= -1 && i < m - 1 && j >= -1 && j < n - 1 && (board[i + 1][j + 1] == 1 || board[i + 1][j + 1] == - 1)) count++;
if(i >= -1 && i < m - 1 && j >= 1 && j < n + 1 && (board[i + 1][j - 1] == 1 || board[i + 1][j - 1] == - 1)) count++;
if(i >= 1 && i < m + 1 && j >= 0 && j < n && (board[i - 1][j] == 1 || board[i - 1][j] == - 1)) count++;
if(i >= 1 && i < m + 1 && j >= -1 && j < n - 1 && (board[i - 1][j + 1] == 1 || board[i - 1][j + 1] == - 1)) count++;
if(i >= 1 && i < m + 1 && j >= 1 && j < n + 1 && (board[i - 1][j - 1] == 1 || board[i - 1][j - 1] == - 1)) count++;
if(count == 3) return true;
else return false;
}else{
int count = 0;
if(i >= 0 && i < m && j >= 1 && j < n + 1 && (board[i][j - 1] == 1 || board[i][j - 1] == - 1)) count++;
if(i >= 0 && i < m && j >= -1 && j < n - 1 && (board[i][j + 1] == 1 || board[i][j + 1] == - 1)) count++;
if(i >= -1 && i < m - 1 && j >= 0 && j < n && (board[i + 1][j] == 1 || board[i + 1][j] == - 1)) count++;
if(i >= -1 && i < m - 1 && j >= -1 && j < n - 1 && (board[i + 1][j + 1] == 1 || board[i + 1][j + 1] == - 1)) count++;
if(i >= -1 && i < m - 1 && j >= 1 && j < n + 1 && (board[i + 1][j - 1] == 1 || board[i + 1][j - 1] == - 1)) count++;
if(i >= 1 && i < m + 1 && j >= 0 && j < n && (board[i - 1][j] == 1 || board[i - 1][j] == - 1)) count++;
if(i >= 1 && i < m + 1 && j >= -1 && j < n - 1 && (board[i - 1][j + 1] == 1 || board[i - 1][j + 1] == - 1)) count++;
if(i >= 1 && i < m + 1 && j >= 1 && j < n + 1 && (board[i - 1][j - 1] == 1 || board[i - 1][j - 1] == - 1)) count++;
if(count < 2) return true;
else if(count == 2 || count == 3) return false;
else return true;
}
}
}
总结:
- 到这题截止,前300题的matrxi题目已经全部刷完了。我感觉matrix题目大多是就是硬算,基本就是遍历矩阵,然后一个个满足条件。matrxi中还涉及不少in-place题目。