<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 DisjointSetsError(Exception):
    pass

class DisjointSetsNode:
    def __init__(self, x):
        self.value = x
        self.parent = self
        self.size = 1

    @staticmethod
    def find(x, splitting=False):
        if splitting:
            while x.parent is not x:
                x.parent, x = x.parent.parent, x.parent
            return x
        else:
            rep = x
            while rep.parent is not rep:
                rep = rep.parent
            while x is not rep:
                x.parent, x = rep, x.parent
            return rep

    @staticmethod
    def union(x, y):
        x = DisjointSetsNode.find(x)
        y = DisjointSetsNode.find(y)
        if x is y:
            return False
        if x.size < y.size:
            x, y = y, x
        y.parent = x
        x.size += y.size
        del y.size
        return True

class DisjointSets:
    def __init__(self):
        self.nodes = {}
        self.count = 0

    def make_set(self, x):
        if x in self.nodes:
            raise DisjointSetsError('Cannot add item that is already present')
        self.nodes[x] = DisjointSetsNode(x)
        self.count += 1

    def __contains__(self, x):
        return x in self.nodes

    def find(self, x, splitting=False):
        if x not in self.nodes:
            raise DisjointSetsError('Item must be present to perform find')
        return DisjointSetsNode.find(self.nodes[x], splitting).value

    def union(self, x, y):
        if x not in self.nodes or y not in self.nodes:
            raise DisjointSetsError('Both items must be present to perform union')
        merged = DisjointSetsNode.union(self.nodes[x], self.nodes[y])
        if merged:
            self.count -= 1
        return merged

    def __len__(self):
        return self.count

class Solution:
    def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:
        m,n = len(matrix),len(matrix[0])
        row_max = [-inf]*m
        col_max = [-inf]*n
        row_rank = [0]*m
        col_rank = [0]*n
        linked = defaultdict(DisjointSets)
        occ = defaultdict(set)
        for i in range(m):
            for j in range(n):
                x = matrix[i][j]
                l = linked[x]
                if (u := (i,False)) not in l:
                    l.make_set(u)
                if (v := (j,True)) not in l:
                    l.make_set(v)
                l.union(u,v)
                occ[x].add((i,j))
        for x in sorted(occ):
            groups = defaultdict(list)
            l = linked[x]
            for i,j in occ[x]:
                groups[l.find((i,False))].append((i,j))
            for group in groups.values():
                rank = 0
                for i,j in group:
                    rank = max(rank,row_rank[i]+(0 if row_max[i] == x else 1),col_rank[j]+(0 if col_max[j] == x else 1))
                for i,j in group:
                    row_max[i] = col_max[j] = x
                    matrix[i][j] = row_rank[i] = col_rank[j] = rank
        return matrix
85800