<p>Given an <code>m x n</code> <code>matrix</code>, return <em>a new matrix </em><code>answer</code><em> where </em><code>answer[row][col]</code><em> is the </em><em><strong>rank</strong> of </em><code>matrix[row][col]</code>.</p>

<p>The <strong>rank</strong> is an <strong>integer</strong> that represents how large an element is compared to other elements. It is calculated using the following rules:</p>

<ul>
	<li>The rank is an integer starting from <code>1</code>.</li>
	<li>If two elements <code>p</code> and <code>q</code> are in the <strong>same row or column</strong>, then:
	<ul>
		<li>If <code>p &lt; q</code> then <code>rank(p) &lt; rank(q)</code></li>
		<li>If <code>p == q</code> then <code>rank(p) == rank(q)</code></li>
		<li>If <code>p &gt; q</code> then <code>rank(p) &gt; rank(q)</code></li>
	</ul>
	</li>
	<li>The <strong>rank</strong> should be as <strong>small</strong> as possible.</li>
</ul>

<p>The test cases are generated so that <code>answer</code> is unique under the given rules.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg" style="width: 442px; height: 162px;" />
<pre>
<strong>Input:</strong> matrix = [[1,2],[3,4]]
<strong>Output:</strong> [[1,2],[2,3]]
<strong>Explanation:</strong>
The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
The rank of matrix[0][1] is 2 because matrix[0][1] &gt; matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][0] is 2 because matrix[1][0] &gt; matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][1] is 3 because matrix[1][1] &gt; matrix[0][1], matrix[1][1] &gt; matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg" style="width: 442px; height: 162px;" />
<pre>
<strong>Input:</strong> matrix = [[7,7],[7,7]]
<strong>Output:</strong> [[1,1],[1,1]]
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg" style="width: 601px; height: 322px;" />
<pre>
<strong>Input:</strong> matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
<strong>Output:</strong> [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m == matrix.length</code></li>
	<li><code>n == matrix[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 500</code></li>
	<li><code>-10<sup>9</sup> &lt;= matrix[row][col] &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution:
    def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:
        m = len(matrix)
        n = len(matrix[0])
        
        # Sort by row and by column
        vals_by_row = [collections.defaultdict(list) for r in range(m)]
        vals_by_col = [collections.defaultdict(list) for c in range(n)]
        for r in range(m):
            for c in range(n):
                val = matrix[r][c]
                ind = r * n + c
                vals_by_row[r][val].append(ind)
                vals_by_col[c][val].append(ind)
        
        # Union-find the cells on the same column or row with identical values
        ind2gp = list(range(m * n))
        gp2ind = {i: [i] for i in range(m * n)}
        
        for dl in [vals_by_row, vals_by_col]:
            for d in dl:
                for k in d:
                    if len(d[k]) > 1:
                        to_merge = d[k]
                        l = len(to_merge)
                        
                        for i in range(1, l):
                            #print(f"Merge {to_merge[i - 1]} with {to_merge[i]}")
                            if (gu := ind2gp[to_merge[i - 1]]) == (gv := ind2gp[to_merge[i]]):
                                continue
                            
                            if len(gp2ind[gu]) < len(gp2ind[gv]):
                                gu, gv = gv, gu
                            
                            for ind in gp2ind[gv]:
                                ind2gp[ind] = gu
                            gp2ind[gu].extend(gp2ind[gv])
                            del(gp2ind[gv])
        
        # Construct edges:
        v = gp2ind.keys()
        out_edges = {i: [] for i in v}
        in_edges = {i: [] for i in v}
        
        for dl in [vals_by_row, vals_by_col]:
            for d in dl:
                asc = sorted(d.keys())
                if len(asc) <= 1:
                    continue
                
                for i in range(1, len(asc)):
                    v1 = ind2gp[d[asc[i - 1]][0]]
                    v2 = ind2gp[d[asc[i]][0]]
                    out_edges[v1].append(v2)
                    in_edges[v2].append(v1)
        
        in_deg = {i: len(in_edges[i]) for i in v}
        #print(out_edges, in_edges, in_deg)
        
        # Topological sort:
        todo = collections.deque([i for i in v if in_deg[i] == 0])
        ranks = dict()
        
        while len(todo):
            curr = todo.popleft()
            ranks[curr] = max(ranks[i] for i in in_edges[curr]) + 1 if len(in_edges[curr]) else 1
            for nxt in out_edges[curr]:
                in_deg[nxt] -= 1
                if in_deg[nxt] == 0:
                    todo.append(nxt)
        
        return [[ranks[ind2gp[r * n + c]] for c in range(n)] for r in range(m)]
    
106900