Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 × 3 grid (one player always draws crosses, the other — noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the game is finished. The player who draws crosses goes first. If the grid is filled, but neither Xs, nor 0s form the required line, a draw is announced.

You are given a 3 × 3 grid, each grid cell is empty, or occupied by a cross or a nought. You have to find the player (first or second), whose turn is next, or print one of the verdicts below: 
 -  illegal — if the given board layout can't appear during a valid game; -  the first player won — if in the given board layout the first player has just won; -  the second player won — if in the given board layout the second player has just won; -  draw — if the given board layout has just let to a draw.
The input consists of three lines, each of the lines contains characters ".", "X" or "0" (a period, a capital letter X, or a digit zero).
def check_winner(board, player):
    for row in board:
        if row == [player]*3:
            return True

    for col in range(3):
        if board[0][col] == player and board[1][col] == player and board[2][col] == player:
            return True


    if board[0][0] == player and board[1][1] == player and board[2][2] == player:
        return True
    if board[0][2] == player and board[1][1] == player and board[2][0] == player:
        return True

    return False

def next_turn(board):
    x_count = sum(row.count("X") for row in board)
    o_count = sum(row.count("0") for row in board)
    empty_count = sum(row.count(".") for row in board)

    
    if x_count < o_count or x_count > o_count + 1:
        return "illegal"

 
    if check_winner(board, "X") and check_winner(board, "0"):
        return "illegal"
    elif check_winner(board, "X"):
        if x_count == o_count + 1:
            return "illegal"
        else:
            return "the first player won"
    elif check_winner(board, "0"):
        if x_count == o_count:
            return "illegal"
        else:
            return "the second player won"
    elif empty_count == 0:
        return "draw"

    if x_count == o_count:
        return "first"
    else:
        return "second"

board = [input() for _ in range(3)]
result = next_turn(board)
print(result)
 		  		   		 	 		 			 	     	