จำลองเกมแห่งชีวิตของคอนเวย์
โจทย์
Initially, there is a grid with some cells which may be alive or dead. Our task is to generate the next generation of cells based on the following rules:
- Any live cell with fewer than two live neighbors dies as if caused by underpopulation.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by overpopulation.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The 1 represents an alive cell and the 0 represents a dead cell.
| Input | Output |
|---|---|
| 4 5 0 1 0 0 1 1 1 0 1 0 0 0 1 0 0 1 0 1 1 1 | 1 1 0 1 0 1 0 0 1 0 0 1 1 0 1 0 1 1 0 1 |
โค้ด
import java.util.*;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
int[][] grid = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = scanner.nextInt();
}
}
int[][] nextGen = simulate(grid, m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(nextGen[i][j] + " ");
}
System.out.println();
}
}
private static int[][] simulate(int[][] grid, int m, int n) {
int[][] nextGrid = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int liveCount = countLiveNeighbors(grid, i, j, m, n);
int currentCell = grid[i][j];
if (currentCell == 1) {
if (liveCount < 2 || liveCount > 3) {
nextGrid[i][j] = 0; // Dies
} else {
nextGrid[i][j] = 1; // Stays alive
}
} else {
if (liveCount == 3) {
nextGrid[i][j] = 1; // Becomes alive
} else {
nextGrid[i][j] = 0; // Stays dead
}
}
}
}
return nextGrid;
}
private static int countLiveNeighbors(int[][] grid, int x, int y, int m, int n) {
int liveCount = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue; // Skip itself
int newX = x + i;
int newY = y + j;
if (isValid(newX, newY, m, n)) {
liveCount += grid[newX][newY];
}
}
}
return liveCount;
}
private static boolean isValid(int x, int y, int m, int n) {
return x >= 0 && x < m && y >= 0 && y < n;
}
}คำอธิบาย
ปรับปรุงล่าสุด