题目描述
输入:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
输出:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
题目分析:就是以二维数组某个元素为中心,寻找周围八个方向的元素,按照题目要求修改二维数组元素返回;
拷贝一份二维数组;
参数分析
void gameOfLife(int** board, int boardSize, int* boardColSize)
**board定义了一个指向整型变量指针的指针,就是二维数组的首地址
boardSize表示行; 4
boardColSize 表示列,每行有多少列 ;== 3
#define DIRECTION_NUM 8
#define DIRECTION_SIZE 2
int directions[DIRECTION_NUM][DIRECTION_SIZE] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};int JudgeLive(int **copyBoard, int rowSize, int colSize, int x, int y)
{int result = 0;for (int i = 0; i < DIRECTION_NUM; i++) {int tempX = x + directions[i][0];//每次按这个方向做偏移int tempY = y + directions[i][1];if (tempX < 0 || tempX >= rowSize || tempY < 0 || tempY >= colSize) {continue;} else {result += copyBoard[tempX][tempY];}}return result;
}void gameOfLife(int** board, int boardSize, int* boardColSize){//外面大的申请一次int **copyBoard = (int **)malloc(sizeof(int *) * boardSize);//循环申请空间for (int i = 0; i < boardSize; i++) {copyBoard[i] = (int *)malloc(sizeof(int) * (*boardColSize));}//给copy的数组赋值for (int i= 0; i < boardSize; i++) {for (int j = 0; j < *boardColSize; j++) {copyBoard[i][j] = board[i][j];}}for (int i= 0; i < boardSize; i++) {for (int j = 0; j < *boardColSize; j++) {int result = JudgeLive(copyBoard, boardSize, *boardColSize, i, j);if (board[i][j] == 0 && result == 3) {board[i][j] = 1;}if (board[i][j] == 1 && (result < 2 || result > 3)) {board[i][j] = 0;}}}
}