코딩 테스트/Level 0
안전지대
컴닥
2022. 11. 8. 15:39
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/120866
파이썬
board와 같은 크기의 check 라는 2차원 리스트를 만들었다.
def solution(board):
check = [[1 for _ in board[0]] for _ in board]
for y in range(len(board)):
for x in range(len(board[0])):
if board[y][x]:
for yy in range(y - 1, y + 2):
for xx in range(x - 1, x + 2):
if 0 <= xx < len(board[0]) and 0 <= yy < len(board):
check[yy][xx] = 0
return sum(sum(each) for each in check)
위 코드가 다중 for문 치고는 단순한 구조라 읽기 어렵진 않지만,
itertools.product 를 이용해도 좋다.
from itertools import product
def solution(board):
check = [[1 for _ in board[0]] for _ in board]
for y, x in product(range(len(board)), repeat=2):
if board[y][x]:
for yy, xx in product(range(y - 1, y + 2), range(x - 1, x + 2)):
if 0 <= xx < len(board[0]) and 0 <= yy < len(board):
check[yy][xx] = 0
return sum(sum(each) for each in check)
개인적으로는 함수당 하나의 기능을 가진 다음과 같은 구조를 선호한다.
from itertools import product
def solution(board):
def check_danger(y, x):
for yy, xx in product(range(y - 1, y + 2), range(x - 1, x + 2)):
if 0 <= xx < len(board[0]) and 0 <= yy < len(board):
check[yy][xx] = 0
def solve():
for y, x in product(range(len(board)), repeat=2):
if board[y][x]:
check_danger(y, x)
return sum(sum(each) for each in check)
check = [[1 for _ in board[0]] for _ in board]
return solve()
함수 내 함수 구조는 객체 지향에서의 프라이빗(private)과 비슷한 느낌도 있다. 외부에서는 check라는 리스트에 접근할 수 없지만
내부의 check_danger 함수와 solve함수는 이를 자유롭게 접근할 수 있다.
코틀린
class Solution {
fun solution(board: Array<IntArray>): Int {
var answer = 0
for (i in board.indices)
for (j in board[0].indices)
if (board[i][j] == 1)
for (k in i - 1..i + 1)
for (l in j - 1..j + 1)
if (k in board.indices && l in board[0].indices && board[k][l] == 0)
board[k][l] = 2
for (i in board.indices)
for (j in board[0].indices)
if (board[i][j] == 0)
answer++
return answer
}
}
반응형