๋ฌธ์
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
- If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
- Otherwise, it becomes vacant.
(Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day 4: [0, 0, 0, 0, 0, 1, 0, 0] Day 5: [0, 1, 1, 1, 0, 1, 0, 0] Day 6: [0, 0, 1, 0, 1, 1, 0, 0] Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000 Output: [0,0,1,1,1,1,1,0]
Note:
- cells.length == 8
- cells[i] is in {0, 1}
- 1 <= N <= 10^9
์ํค๋ ๋ฐ๋ก ๊ตฌํํ๋ค.
N ์ด 1000000000 ์ผ๋ก ์ต์ด ๋์ด๊ฐ๋ ๋ฒ์์ด๋ค.
์ผ๋ฐ์ ์ผ๋ก 1์ต๋ฒ ์คํ์ด 1์ด์ ๋ ๊ฑธ๋ฆฐ๋ค๊ณ ์๊ฐํ๊ณ
๋๋ถ๋ถ ์ฝ๋ฉ๋ฌธ์ ๋ 1์ด ์์ ์คํ๋์ด์ผ Time Limit ์ด ์๊ฑธ๋ฆฐ๋ค๊ณ ์๊ณ ๋ฆฌ์ฆ ์ํ์๋ ํ์๊ฒ ๋ค์๋ค.
N๋ฒ for ๋ฌธ ๋๋ฆฌ๋ Time Limit ์ด ๊ฑธ๋ฆฐ๋ค.
์ด๋์ ์ด๋ป๊ฒ ์๊ฐ์ ์ค์ฌ์ผ ํ ๊น ๊ฒ๋ ์๊ฐํด๋ ๋ฐ๋ณต๋ฌธ ํ๋์ธ๋ฐ ๋ญ ๋ ์ด๋ป๊ฒ ์ค์ผ๊น ์ถ์๋ค.
์ด์จ๊ฑด ์๊ฐ์ ์ค์ผ๋ ค๋ฉด N๋ฒ ์ ๋ถ ๋ฐ๋ณต๋ฌธ์ ๋์ง ๋ง๋ผ๋ ์๊ธฐ์ธ๊ฒ ๊ฐ์ N๋ฒ์ ๋ค ๋์ง ์๊ณ ๋
๊ฒฐ๊ณผ๊ฐ์ ์ฐพ์ ์ ์์ ์ง ์๊ฐํ๋ค.
์ํ์ ์ผ๋ก ์์์ด ์๋์ง ์๊ฐํด๋ณด์๊ณ ์ด๋ค ํจํด์ด ์๋์ง๋ ํ์ธํด ๋ณด์๋ค.
ํจํด์ด ์์๋ค.
14๋ฒ ๋จ์๋ก ๊ฐ์ ํจํด์ด ๋ฐ๋ณต๋๊ณ ์์๋ค.
๊ทธ๋ผ 14๋ฒ๊น์ง๋ง ๋ฐ๋ณต๋ฌธ์ ๋๊ณ ๊ฒฐ๊ณผ๋ 14๋ฅผ ๋๋ ๋๋จธ์ง ๊ฐ์ ์ฌ์ฉํ๋ฉด ๋ ๐
class Solution {
var arr : [Int] = []
func prisonAfterNDays(_ cells: [Int], _ N: Int) -> [Int] {
arr = cells
var answer : [[Int]] = []
// print(arr)
for i in 0..<N{
if (i > 14){
break
}
answer.append(check())
}
// print(answer)
// for i in answer{
// print(i)
// }
// print(answer[0])
if N%14 != 0 {
return answer[N%14 - 1]
}else{
return answer[13]
}
}
func check() -> [Int] {
var tmp : [Int] = arr
tmp[0] = 0
tmp[7] = 0
for i in 1...6 {
if arr[i-1] == 0 && arr[i+1] == 0 {
tmp[i] = 1
}else if arr[i-1] == 1 && arr[i+1] == 1 {
tmp[i] = 1
}else{
tmp[i] = 0
}
}
arr = tmp
// print(arr)
return arr
}
}
'Algorithm > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฏ Daily LeetCode Challenge Day_05 - Hamming Distance (2) | 2020.07.06 |
---|---|
๐ฏ Daily LeetCode Challenge Day_04 - Ugly Number II (0) | 2020.07.06 |
๐ฏ Daily LeetCode Challenge Day_02 - Binary Tree Level Order Traversal II (0) | 2020.07.03 |
๐ฏ Daily LeetCode Challenge Day_01 - Arranging Coins (0) | 2020.07.01 |
LeetCode - 994. Rotting Oranges (0) | 2020.06.01 |
๋๊ธ