HackerRank "Bot Saves Princess" beginner code
The function should be path_to_princess(grid), using the naming convention specified in PEP 8.  The n parameter is redundant, as it can be inferred from the grid's dimensions.  In any case, redefining n=n-1 is confusing.  Also, it would be better to leave all I/O out of the function, so that it just does computation.

The while(flag) loop shouldn't exist.  If the princess is in another castle, you'll end up with an infinite loop; otherwise, the code executes just once.

Use the // operator for integer division.

Explicit looping can be greatly reduced through liberal use of list comprehensions, generators, and list multiplication.

def path_to_princess(grid):
    z = len(grid) - 1
    corners = [
        (0, 0), (0, z),
        (z, 0), (z, z)
    ]
    p = next((r, c) for r, c in corners if grid[r][c] == 'p')
    m = (z // 2, z // 2)
    row_diff, col_diff = p[0] - m[0], p[1] - m[1]    
    yield from (['UP'] * -row_diff if row_diff &lt; 0 else ['DOWN'] * row_diff)
    yield from (['LEFT'] * -col_diff if col_diff &lt; 0 else ['RIGHT'] * col_diff)

n = int(input())
grid = [input().strip() for _ in range(n)]
for move in path_to_princess(grid):
    print(move)