Hackerrank "Bot saves princess" AI problem in python3

i’m trying to solve this challenge in Hackerrank Challenge
But it’s not work properly, Can you please help me to figure out what’s wrong with my code?

def displayPathtoPrinces(n,grid):
    if grid[0][0] == 'p':
        print("UP")
        print("LEFT")
    elif grid[0][n - 1] == 'p':
        print("UP")
        print("RIGHT")
    elif grid[n - 1][0] == 'p':
        print("DOWN")
        print("LEFT")
    else:
        print("DOWN")
        print("RIGHT")

m = int(input())
grid = []
for i in range(0,m):
    grid.append(input().strip())

displayPathtoPrinces(m,grid)