标签:++ livecount 细胞 289 int Algorithms board && leetcode
原题
思路
这个因为是瞬时变化,要变一起变,所以不能在原数组上操作。
NEW一个新的数组,然后循环判断,左上,上,右上,左,右,左下,下,右下。
再根据条件进行判断是生是死。
代码一把过,本来感觉可能要执行的很慢,结果是击败百分之百,很开心。
代码
package leetcode.Algorithms;
public class Solution_289 {
public static void main(String[] args) {
int[][] board = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
gameOfLife(board);
}
public static void gameOfLife(int[][] board) {
int[][] copy = new int[board.length][board[0].length];
int x = board.length;
int y = board[0].length;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
int livecount = 0;
//左上角
if (i - 1 >= 0 && j - 1 >= 0) {
if (board[i - 1][j - 1] > 0) {
livecount++;
}
}
//中上
if (i - 1 >= 0) {
if (board[i - 1][j] > 0) {
livecount++;
}
}
//右上
if (i - 1 >= 0 && j + 1 < y) {
if (board[i - 1][j + 1] > 0) {
livecount++;
}
}
//左
if (j - 1 >= 0) {
if (board[i][j - 1] > 0) {
livecount++;
}
}
//右
if (j + 1 < y) {
if (board[i][j + 1] > 0) {
livecount++;
}
}
//左下
if (i + 1 < x && j - 1 >= 0) {
if (board[i + 1][j - 1] > 0) {
livecount++;
}
}
//下
if (i + 1 < x) {
if (board[i + 1][j] > 0) {
livecount++;
}
}
//右下
if (i + 1 < x && j + 1 < y) {
if (board[i + 1][j + 1] > 0) {
livecount++;
}
}
// * 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
// * 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
// * 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
// * 如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
if (livecount > 3) {
copy[i][j] = 0;
} else if (livecount < 2) {
copy[i][j] = 0;
} else if (livecount == 3 && board[i][j] == 0) {
copy[i][j] = 1;
} else if ((livecount == 2 || livecount == 3) && board[i][j] == 1) {
copy[i][j] = 1;
}
}
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
board[i][j] = copy[i][j];
}
}
}
}
标签:++,livecount,细胞,289,int,Algorithms,board,&&,leetcode 来源: https://blog.csdn.net/qq_38173650/article/details/119354168
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。