2615_오목

Hongil Son·2022년 7월 4일
0

알고리즘

목록 보기
1/19

입력

0, 1, 2로 이루어진 19x19 오목판

출력

첫 번째 줄에는 5개가 연속된 숫자 혹은 0을 출력
두 번째 줄에는 연속된 5개 오목알 중 가장 왼쪽에 위치한 오목알의 좌표

조건

  • 오목판의 사이즈가 19x19로 제한
  • 정확히 5개가 연속된 경우만 stop
  • 가장 왼쪽에 위치한 오목돌의 위치를 출력

풀이

  1. 가장 왼쪽에 위치한 오목돌을 찾기 위해 y축을 우선 탐색
  2. 직선 방향과 대각 방향 전부를 확인하기 위해 두 가지 x축, y축 방향을 설정 후 탐색
line_dx = [-1, 0, 1, 0]
line_dy = [0, -1, 0, 1]
opp_dx = [-1, -1, 1, 1]
opp_dy = [-1, 1, -1, 1]
...
for idx in range(4):
    if cons_check(board, [line_dy[idx], line_dx[idx]], color, [y, x]):
    ans[0], ans[2] = color, x
    dx, dy = line_dx[idx], line_dy[idx]
    end = True
    break

    if cons_check(board, [opp_dy[idx], opp_dx[idx]], color, [y, x]):
    ans[0], ans[2] = color, x
    dx, dy = opp_dx[idx], opp_dy[idx]
    end = True
    break
  1. 연속된 오목알을 찾기(cons_check()) -> 5개일 경우 시작점 기준으로 반대 방향에 같은 색깔의 오목알이 존재하는지 확인(opp_check())
def cons_check(board, way, color, start):
    _start = copy.deepcopy(start)
    _color = color
    dx = way[1]
    dy = way[0]
    _flag = 1

    while True:
        if _start[0]+dy >= 0 and _start[0]+dy < 19 and _start[1]+dx >= 0 and _start[1]+dx < 19:
            _start[0] += dy
            _start[1] += dx

            if board[_start[0]][_start[1]] == _color: _flag += 1
            else: break

        else: break

    if _flag == 5 and opp_check(board, way, color, start): return True
    else: return False

def opp_check(board, way, color, start):
    _start = copy.deepcopy(start)
    _color = color
    if way[0] == 1: dy = -1
    elif way[0] == -1: dy = 1
    else: dy = 0

    if way[1] == 1: dx = -1
    elif way[1] == -1: dx = 1
    else: dx = 0

    if _start[0]+dy >= 0 and _start[0]+dy < 19 and _start[1]+dx >= 0 and _start[1]+dx < 19:
        _start[0] += dy
        _start[1] += dx
    else: return True

    if board[_start[0]][_start[1]] != _color: return True
    else: return False

전체 코드

오목

profile
pushing

0개의 댓글