문제
Each cell is alive (1) or dead (0) and has up to 8 neighbors. In the next generation a live cell survives with 2 or 3 live neighbors, and a dead cell becomes alive with exactly 3. Cells outside the grid are dead. All cells update at the same time.
Implement next_generation(grid).
Input
grid: A rectangular grid of 0s and 1s.
Output
Return the next generation.
제약 조건
0 ≤ rows, columns ≤ 200
예시
입력:
grid = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
]
예상 출력:
expected = [
[0, 0, 0],
[1, 1, 1],
[0, 0, 0]
]
입력:
std::vector<std::vector<long long>> grid = {
{0, 1, 0},
{0, 1, 0},
{0, 1, 0}
};
예상 출력:
std::vector<std::vector<long long>> expected = {
{0, 0, 0},
{1, 1, 1},
{0, 0, 0}
};
입력:
long[][] grid = new long[][] {
new long[] {0, 1, 0},
new long[] {0, 1, 0},
new long[] {0, 1, 0}
};
예상 출력:
long[][] expected = new long[][] {
new long[] {0, 0, 0},
new long[] {1, 1, 1},
new long[] {0, 0, 0}
};
설명
The vertical "blinker" turns horizontal: the center survives and its left and right neighbors are born, filling the middle row.
입력:
grid = [
[1, 1],
[1, 1]
]
예상 출력:
expected = [
[1, 1],
[1, 1]
]
입력:
std::vector<std::vector<long long>> grid = {
{1, 1},
{1, 1}
};
예상 출력:
std::vector<std::vector<long long>> expected = {
{1, 1},
{1, 1}
};
입력:
long[][] grid = new long[][] {
new long[] {1, 1},
new long[] {1, 1}
};
예상 출력:
long[][] expected = new long[][] {
new long[] {1, 1},
new long[] {1, 1}
};
설명
Every cell of the 2×2 block has 3 neighbors, so the block stays the same.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
모든 셀이 동시에 바뀌므로, 다음 상태는 부분 업데이트된 값이 아니라 원래 그리드를 기준으로 계산해야 합니다.
힌트 2
각 셀의 살아 있는 이웃 수를 세고, 생존/탄생 규칙을 적용해 새 그리드를 만드세요.
힌트 3
가장자리 셀은 그리드 밖 이웃을 죽은 셀로 취급해야 하고, 셀 자기 자신은 이웃 수에 포함하면 안 됩니다.
예상 복잡도
시간 O(rows × columns), 추가 공간 O(rows × columns)
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.