입출력 예시
board | result |
["O.X", ".O.", "..X"] | 1 |
["OOO", "...", "XXX"] | 0 |
["...", ".X.", "..."] | 0 |
["...", "...", "..."] | 1 |
나의 코드
def solution(board):
def bingo_counter(board, horse):
bingo = 0
# possible bingo
pos = [[(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], # row
[(0, 0), (1, 1), (2, 2)], [(0, 2), (1, 1), (2, 0)], # diag
[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]] # col
for case in pos:
temp = []
for (a, b) in case:
temp.append(board[a][b])
if temp.count(horse) == 3:
bingo += 1
return bingo
# count O and X
no = 0
nx = 0
for r in board:
no += r.count('O')
nx += r.count('X')
if not (nx <= no <= nx+1):
return 0
else:
n_bingo_o = bingo_counter(board, 'O')
n_bingo_x = bingo_counter(board, 'X')
# print(n_bingo_o), print(n_bingo_x)
if n_bingo_o:
if (nx + 1 != no):
return 0
if n_bingo_x:
if (nx != no):
return 0
if n_bingo_o and n_bingo_x:
return 0
return 1
Python
복사
다른 풀이
def check_win(player, board):
# Check rows
for i in range(3):
if all(cell == player for cell in board[i]):
return True
# Check columns
for j in range(3):
if all(board[i][j] == player for i in range(3)):
return True
# Check diagonals
if all(board[i][i] == player for i in range(3)):
return True
if all(board[i][2-i] == player for i in range(3)):
return True
return False
def solution(board):
num_x = sum(row.count('X') for row in board)
num_o = sum(row.count('O') for row in board)
if num_x - num_o > 0 or abs(num_x - num_o) > 1:
return 0
elif (check_win('O', board) and num_x != num_o - 1) or (check_win('X', board) and num_x != num_o):
return 0
return 1
Python
복사
개선점 분석
•
전략은 동일
1.
O의 개수와 X의 개수를 확인: num_x ≤ num_o ≤ num_x + 1 을 만족해야 함.
2.
빙고가 있을 경우 O의 갯수와 X의 갯수 조건을 다시 확인
i.
O의 빙고가 있을 경우, num_o = num_x - 1 이어야 함.
ii.
X의 빙고가 있을 경우, num_o = num_x 이어야 함.
•
빙고를 체크할 때 all() 함수를 써서 확인하는 technique 기억!
•
마지막 조건 (if n_bingo_o and n_bingo_x: return 0)은 필요 없었음.
def check_win(board, horse):
# check rows
for i in range(3):
if all(cell == horse for cell in board[i]):
return True
# check cols
for j in range(3):
if all(board[i][j] == horse for i in range(3)):
return True
# check diagonals
if all(board[i][i] == horse for i in range(3)):
return True
if all(board[i][2-i] == horse for i in range(3)):
return True
return False
def solution(board):
num_x = sum(row.count('X') for row in board)
num_o = sum(row.count('O') for row in board)
if not (num_x <= num_o <= num_x + 1):
return 0
if (check_win(board, 'O') and num_o != num_x + 1):
return 0
if (check_win(board, 'X') and num_o != num_x):
return 0
return 1
Python
복사