<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])
        
        def find_root(x: int, y: int):
            if parent[x][y] == (x, y):
                return (x, y)
            else:
                r = find_root(parent[x][y][0], parent[x][y][1])
                parent[x][y] = r
                return r
        
        def union(x1, y1, x2, y2):
            root_a = find_root(x1, y1)
            root_b = find_root(x2, y2)
            parent[root_b[0]][root_b[1]] = root_a
            
        ########################################################
        
		# *parent* records the parent of each point in matrix form
		# points with same value in the same row/column should have the same parent
        parent = [[(j, i) for i in range(n)] for j in range(m)]
        
		# sort each row, if there are points with same value, union them
        for i in range(m):
            value = []
            for j in range(n):
                v = tuple([matrix[i][j], i, j])
                value.append(v)
            value.sort()
            for k in range(n - 1):
                if value[k][0] == value[k + 1][0]:
                    union(value[k][1], value[k][2], value[k + 1][1], value[k + 1][2])
					
        # sort each column, if there are points with same value, union them            
        for i in range(n):
            value = []
            for j in range(m):
                v = tuple([matrix[j][i], j, i])
                value.append(v)
            value.sort()
            for k in range(m - 1):
                if value[k][0] == value[k + 1][0]:
                    union(value[k][1], value[k][2], value[k + 1][1], value[k + 1][2])
        
        ########################################################
        
        dic = {} # point index : point that it directs ->
        in_degree = {} # point index : number of incoming arrows <-
		
		# Ex. [20, -21, 14]
		# sort: -21 (0, 1) -> 14 (0, 2) -> 20 (0, 0)
		# dic = { (0, 0) : [], (0, 1) : [(0, 2)], (0, 2) : [(0, 0)] }
		# in_degree = { (0, 0) : 1, (0, 1) : 0, (0, 2) : 1 }
		
		# only select "root" points that parent[point] = point itself
        for i in range(m):
            for j in range(n):
                if parent[i][j] == (i, j):
                    dic[(i, j)] = []
                    in_degree[(i, j)] = 0
                    
		# if there are points that parent[point] = its parent but not the "root" ancestor
		# make parent[point] = the "root" ancestor
		
		# Ex. before: parent[4][4] = (4, 4), parent[8][0] = (4, 4), parent[8][4] = (8, 0)
		# after: parent[4][4] = (4, 4), parent[8][0] = (4, 4), parent[8][4] = (4, 4)
		
        for i in range(m):
            for j in range(n):
                while parent[i][j] not in dic:
                    parent[i][j] = parent[parent[i][j][0]][parent[i][j][1]]
        
		# continue to construct *dic* and *in_degree*
		# make connections in each row
        for i in range(m):
            row = []
            for j in range(n):
                r = tuple([matrix[i][j], parent[i][j][0], parent[i][j][1]])
                row.append(r)
            row.sort()
            for k in range(n - 1):
                if row[k][0] < row[k + 1][0]:
                    if (row[k][1], row[k][2]) in dic and (row[k + 1][1], row[k + 1][2]) in dic:
                        if (row[k + 1][1], row[k + 1][2]) not in dic[(row[k][1], row[k][2])]:
                            dic[(row[k][1], row[k][2])].append((row[k + 1][1], row[k + 1][2]))
                            in_degree[(row[k + 1][1], row[k + 1][2])] += 1
        
		# and make connections in each column
        for i in range(n):
            col = []
            for j in range(m):
                c = tuple([matrix[j][i], parent[j][i][0], parent[j][i][1]])
                col.append(c)
            col.sort()
            for k in range(m - 1):
                if col[k][0] < col[k + 1][0]:
                    if (col[k][1], col[k][2]) in dic and (col[k + 1][1], col[k + 1][2]) in dic:
                        if (col[k + 1][1], col[k + 1][2]) not in dic[(col[k][1], col[k][2])]:
                            dic[(col[k][1], col[k][2])].append((col[k + 1][1], col[k + 1][2]))
                            in_degree[(col[k + 1][1], col[k + 1][2])] += 1
        
        #######################################################################
        
		# *distance* records the rank of the "root" points (just my naming habit)
        distance = {} # point index : rank
        for i in range(m):
            for j in range(n):
                if parent[i][j] == (i, j):
                    distance[(i, j)] = 0
        
		# first put "root" points that have 0 in_degree (meaning they are the smallest) in queue
        queue = []
        for i in in_degree:
            if in_degree[i] == 0:
                queue.append(i)
                distance[i] = 1
        
        head = 0
        tail = len(queue) - 1
        while head <= tail:
            h = queue[head]

            for p in dic[h]:
                in_degree[p] -= 1
                if in_degree[p] == 0:
                    queue.append(p)
                    distance[p] = distance[h] + 1

            head += 1
            tail = len(queue) - 1
        
        #######################################################################
        
		# *rank* records the final result in matrix form
        rank = [[0 for i in range(n)] for j in range(m)]
        
		# now we already got the rank of those "root" points recorded in *distance*
		# let's put them in *rank*, also their descendants'
        for i in range(m):
            for j in range(n):
                rank[i][j] = distance[parent[i][j]]
        
        return rank
64800