矩阵中遍历某个点周围的九个点
目录
矩阵中遍历某个点周围的九个点
又是学习新知识的一天,以下为Java版本部分关键代码
int[] neighbors = {0, 1, -1};
int rows = board.length;
int cols = board[0].length;
int[][] copyBoard = new int[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int liveNeighbors = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (!(neighbors[i] == 0 && neighbors[j] == 0)) {
//计算行和列 2,2 2,3 2 1 1,1,1,2,1,3
int r = (row + neighbors[i]);
int c = (col + neighbors[j]);
if ((r < rows && r >= 0) && (c < cols && c >= 0) && (copyBoard[r][c] == 1)) {
liveNeighbors++;
}
}
}
}
}
}