import heapq
class Solution:
    def swimInWater(self, grid):
        n = len(grid)
        if n == 0: return 0
        visited = [[0 for i in range(n)] for j in range(n)]
        max_number = 0
        q = [[grid[0][0], 0, 0]]
        directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        visited[0][0] = 1
        while len(q)!=0:
            heapq.heapify(q)
            val, i, j = heapq.heappop(q)
            max_number = max(max_number, val)
            if i==n-1 and j==n-1: return max_number
            for ii, jj in directions:
                x = i+ii
                y = j+jj
                if not(0<=x<n and 0<=y<n):
                    continue
                if visited[x][y] == 0:
                    visited[x][y] = 1
                    q.append([grid[x][y], x, y])
        return max_number