Help me in solving ICL16AA problem

My issue

time limit exceeded

My code

import heapq

def max_letter_diff(row1, row2):
    return max(abs(ord(row1[i]) - ord(row2[i])) for i in range(len(row1)))

def min_largest_cost(n, m, grid):
    # Initialize distances with infinity
    dist = [float('inf')] * n
    dist[0] = 0  # The cost to mark the first row is zero

    # Priority queue to process rows by minimum cost
    pq = [(0, 0)]  # (cost, row_index)
    
    while pq:
        current_cost, u = heapq.heappop(pq)
        
        if current_cost > dist[u]:
            continue
        
        for v in range(n):
            if u != v:
                cost = max_letter_diff(grid[u], grid[v])
                if max(current_cost, cost) < dist[v]:
                    dist[v] = max(current_cost, cost)
                    heapq.heappush(pq, (dist[v], v))
    
    return max(dist)

def main():
    n, m = map(int, input().split())
    grid = [input().strip() for _ in range(n)]
    
    result = min_largest_cost(n, m, grid)
    print(result)

if __name__ == "__main__":
    main()

Learning course: Analysis and Design of Algorithms
Problem Link: Fullmetal Alchemist in Analysis and Design of Algorithms