Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.” • https://zh.wikipedia.org/wiki/%E5%BA %B7%E5%A8%81%E7%94%9F%E5%91%BD %E6%B8%B8%E6%88%8F • ߁Җੜ໋༡ፍ
cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): • څ㟬Ұݸm x n త൫໘ɼ㑌ݸ֨ࢠ༗Ұݸى࢝㐫 ଶɼ׆(1) ҃ ࢮ(0)ɻ㑌ݸ֨ࢠଞతീݸᬠډʢ্Լ ࠨӈɼؐ༗ࣼʣಁաԼ໘࢛ᑍنଇޓಈɻ
dies, as if caused by under-population. • ׆త֨ࢠɼՌ༗গԙၷݸ׆తᬠډɼ။ଠݽᘐࣕ ࢮɻ • Any live cell with two or three live neighbors lives on to the next generation. • ׆త֨ࢠɼՌ༗ၷ҃ࡾݸ׆తᬠډɼ။᠃׆Լ ڈɻ
dies, as if by over-population.. • ׆త֨ࢠɼՌ༗աࡾݸ׆తᬠډɼ။ଠ༴Ꮀࣕࢮɻ • Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. • ࢮత֨ࢠɼՌ༗߶ࡾݸ׆తᬠډɼब။෮׆ɻ
in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. • ՄҎෆ༻ֹ֎ۭؒ(in-place) ိ႔ཧ䆩ʁهॅɼॴ ༗త֨ࢠཁҰ࣍႔ཧɼෆՄҎઌ႔ཧҰࠣɼ࠶༻ଞ ၇৽తᆴိ႔ཧଖଞ֨ࢠɻ
2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? • ࡏṜཫ໘ɼզ၇༻ೋҡਞྻိදࣔ֨ࢠɻୠଖመ൫ ໘جຊ্ੋແݶେతɼ༻ਞྻతࡏᬑ㐊႔။༗ɼ Ṝݸ㟬။ዎኄղܾ䏆ʁ
{…} func gameOfLife(_ board: inout [[Int]]) { var numNeighbors:[[Int]] = board for y in 0..<board.count { for x in 0..<board[0].count { numNeighbors[y][x] = countLiveNeighbor(x: x, y: y, board: board) } } for y in 0..<board.count { for x in 0..<board[0].count { switch numNeighbors[y][x] { case 2: continue case 3: board[y][x] = 1 default: board[y][x] = 0 } } } } } ׆ᬠډᏐ 2 3 ଖଞ ׆(1) ׆(1) ׆(1) ࢮ(0) ࢮ(0) ࢮ(0) ׆(1) ࢮ(0) Time Complexity: O(m*n) Space Complexity: O(m*n) Run Time: 25ms
{…} func gameOfLife(_ board: inout [[Int]]) { for y in 0..<board.count { for x in 0..<board[0].count { board[y][x] += 2 * countLiveNeighbor(x: x, y: y, board: board) } } for y in 0..<board.count { for x in 0..<board[0].count { switch board[y][x]/2 { case 2: board[y][x] = board[y][x]%2 case 3: board[y][x] = 1 default: board[y][x] = 0 } } } } } ׆ᬠډᏐ 2 3 ଖଞ ׆(1) ׆(1) ׆(1) ࢮ(0) ࢮ(0) ࢮ(0) ׆(1) ࢮ(0) Time Complexity: O(m*n) Space Complexity: O(1) Run Time: 42ms