stones
: 바둑알 위치 정보
19 * 19 로 주어지는 바둑알 상태 정보를 통해 누가 이겼는지, 승부가 났는지 여부를 출력하는 문제이다.
⭐️ 오목 게임 방법
- 상태 의미 :
1
→ 검은 바둑알,2
→ 흰 바둑알,0
→ 바둑알 없는 곳- 같은 색이 연속 다섯 알 놓이면 🏆⭕️, 여섯 알 이상은 🏆❌
- 연속적 = 가로, 세로, 대각선 방향 연달아 위치함
- 2가지 색이 동시에 이기거나, 1가지 색이 2곳에서 이기는 경우는 ❌
- 승부가 났을 경우, 이긴 바둑알의 가장 왼쪽에 있는 바둑알의 가로줄 번호와 세로줄 번호를 순서대로 출력
문제에서 의해 2곳에서 이기는 경우는 없다고 했으므로 바둑판 상태 정보를 처음부터 확인한다.
바둑알이 있는 경우에 아래와 같이 승패를 판단한다.
+1
한 값 반환전체 바둑판 확인 →
BFS 함수로 오목 확인 →
최종 시간복잡도
으로 최악의 경우에도 1초 내에 연산 가능하다.
바둑판 전체를 BFS로 탐색하면서 오목 찾기
#### 수정 전
# 5개 뿐이면 색 출력
print(color)
answer_x, answer_y = x, y
return answer_x + 1, answer_y + 1
#### 수정 후
# 5개면 승리이므로 원하는 결과 출력
print(color)
return answer_x + 1, answer_y + 1
# 승리 아무도 못함
return -1, -1
-1, -1
가 되도록 해서 승리 결정 여부를 확인했다.# 바둑알 위치 확인
answer_x, answer_y = -1, -1
for i in range(19):
for j in range(19):
if stones[i][j] != 0:
answer_x, answer_y = bfs(i, j)
answer_x
, answer_y
에 들어가 원하는 값을 얻을 수 없었다.import sys
from collections import deque
input = sys.stdin.readline
# 4가지 방향 정의 : 가로, 세로, 대각선 아래, 대각선 위
directions = [(0, 1), (1, 0), (1, 1), (-1, 1)]
def bfs(x, y):
# 색 저장
color = stones[x][y]
# 탐색
for direction in directions:
queue = deque([(x, y)])
count = 1
answer_x, answer_y = x, y
while queue:
cx, cy = queue.popleft()
nx, ny = cx + direction[0], cy + direction[1]
# 바둑판 범위 안에 있고 같은 색이면 탐색
if 0 <= nx < 19 and 0 <= ny < 19 and stones[nx][ny] == color:
count += 1
queue.append((nx, ny))
# 6개 이상인지 확인
if count == 5:
# 육목 체크
if 0 <= x - direction[0] < 19 and 0 <= y - direction[1] < 19 and stones[x - direction[0]][y - direction[1]] == color:
break
if 0 <= nx + direction[0] < 19 and 0 <= ny + direction[1] < 19 and stones[nx + direction[0]][ny + direction[1]] == color:
break
# 5개면 승리이므로 원하는 결과 출력
print(color)
return answer_x + 1, answer_y + 1
# 승리 아무도 못함
return -1, -1
# 바둑 상태 입력
stones = [list(map(int, input().split())) for _ in range(19)]
# 바둑알 위치 확인
answer_x, answer_y = -1, -1
for i in range(19):
for j in range(19):
if stones[i][j] != 0:
answer_x, answer_y = bfs(i, j)
if answer_x != -1 and answer_y != -1:
break
if answer_x != -1 and answer_y != -1:
break
# 결과 출력
if answer_x == -1 and answer_y == -1:
print(0)
else:
print(answer_x, answer_y)