Rook (Codeforces 1907A)
Tags: Implement, implementation

As you probably know, chess is a game that is played on a board with 64 squares arranged in an $$$8\times 8$$$ grid. Columns of this board are labeled with letters from a to h, and rows are labeled with digits from 1 to 8. Each square is described by the row and column it belongs to.  The rook is a piece in the game of chess. During its turn, it may move any non-zero number of squares horizontally or vertically. Your task is to find all possible moves for a rook on an empty chessboard.

Input: The first line of input contains single integer $$$t$$$ ($$$1 \le t \le 64$$$) — the number of test cases. The descriptions of test cases follow.Each test case contains one string of two characters, description of the square where rook is positioned. The first character is a letter from a to h, the label of column, and the second character is a digit from 1 to 8, the label of row. The same position may occur in more than one test case.

Output: For each test case, output descriptions of all squares where the rook can move, in the same format as in the input. You can output squares in any order per test case.


Sample Inputs:
1
d5

Sample Outputs:
d1
d2
b5
g5
h5
d3
e5
f5
d8
a5
d6
d7
c5
d4

Solution (Python):
def rook_moves(square):
    moves = []
    (col, row) = (square[0], int(square[1]))
    for i in range(1, 9):
        if i != row:
            moves.append(col + str(i))
    for c in 'abcdefgh':
        if c != col:
            moves.append(c + str(row))
    return moves
if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        square = input().strip()
        moves = rook_moves(square)
        for move in moves:
            print(move)

Solution (Python):
t = int(input())
for i in range(t):
    n = input()
    l = []
    a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    l.append(n[0])
    l.append(int(n[1]))
    for i in range(0, 8):
        if a[i] != n[0]:
            print(a[i], n[1], sep='')
    for j in range(1, 9):
        if j != l[1]:
            print(n[0], j, sep='')

Solution (Python):
def find_rook_moves(square):
    moves = []
    col = square[0]
    row = int(square[1])
    for c in 'abcdefgh':
        if c != col:
            moves.append(c + str(row))
    for r in range(1, 9):
        if r != row:
            moves.append(col + str(r))
    return moves
t = int(input())
for _ in range(t):
    square = input()
    moves = find_rook_moves(square)
    for move in moves:
        print(move)