<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>

from collections import defaultdict
from typing import List

class UnionFind:
    def __init__(self):
        self.parent = {}
        self.rank = {}

    def find(self, x):
        # Path compression
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        # Union by rank
        if x not in self.parent:
            self.parent[x] = x
            self.rank[x] = 0
        if y not in self.parent:
            self.parent[y] = y
            self.rank[y] = 0
        
        x_root = self.find(x)
        y_root = self.find(y)
        
        if x_root != y_root:
            if self.rank[x_root] > self.rank[y_root]:
                self.parent[y_root] = x_root
            elif self.rank[x_root] < self.rank[y_root]:
                self.parent[x_root] = y_root
            else:
                self.parent[y_root] = x_root
                self.rank[x_root] += 1

class Solution:
    def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:
        m, n = len(matrix), len(matrix[0])  # Get the dimensions of the matrix
        
        answer = [[0] * n for _ in range(m)]  # Initialize answer matrix with zeros
        value_to_positions = defaultdict(list)

        # Group positions by their values
        for r in range(m):
            for c in range(n):
                value_to_positions[matrix[r][c]].append((r, c))

        row_max = [0] * m  # Initialize maximum rank for each row
        col_max = [0] * n  # Initialize maximum rank for each column

        for value in sorted(value_to_positions):  # Process each value in sorted order
            uf = UnionFind()  # Create a new UnionFind instance for each unique value
            component = {}
            
            # Link all positions with the same value
            for r, c in value_to_positions[value]:
                uf.union((r, 'row'), (c, 'col'))
            
            # Find the maximum rank in each connected component
            for r, c in value_to_positions[value]:
                root = uf.find((r, 'row'))
                if root not in component:
                    component[root] = max(row_max[r], col_max[c]) + 1
                else:
                    component[root] = max(component[root], max(row_max[r], col_max[c]) + 1)
            
            # Assign the calculated rank to the positions
            for r, c in value_to_positions[value]:
                root = uf.find((r, 'row'))
                answer[r][c] = component[root]
                row_max[r] = max(row_max[r], answer[r][c])
                col_max[c] = max(col_max[c], answer[r][c])

        return answer


class UnionFind2:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])  # Path compression
        return self.parent[x]

    def union(self, x, y):
        x_root = self.find(x)
        y_root = self.find(y)
        if x_root != y_root:
            if self.rank[x_root] > self.rank[y_root]:
                self.parent[y_root] = x_root
            elif self.rank[x_root] < self.rank[y_root]:
                self.parent[x_root] = y_root
            else:
                self.parent[y_root] = x_root
                self.rank[x_root] += 1


class Solution2:
    def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:
        m, n = len(matrix), len(matrix[0])  # Get the dimensions of the matrix

        answer = [[0] * n for _ in range(m)]  # Initialize answer matrix with zeros

        value_to_positions = defaultdict(list)

        # Group positions by their values
        for r in range(m):
            for c in range(n):
                value_to_positions[matrix[r][c]].append((r, c))

        row_max = [0] * m  # Initialize maximum rank for each row
        col_max = [0] * n  # Initialize maximum rank for each column

        for value in sorted(value_to_positions):  # Process each value in sorted order
            uf = UnionFind2(m + n)  # Create a UnionFind object

            # Link all positions with the same value
            for r, c in value_to_positions[value]:
                uf.union(r, m + c)

            # Find the maximum rank in each connected component
            component = {}
            for r, c in value_to_positions[value]:
                root = uf.find(r)
                if root not in component:
                    component[root] = max(row_max[r], col_max[c]) + 1
                else:
                    component[root] = max(component[root], max(row_max[r], col_max[c]) + 1)

            # Assign the calculated rank to the positions
            for r, c in value_to_positions[value]:
                root = uf.find(r)
                answer[r][c] = component[root]
                row_max[r] = max(row_max[r], answer[r][c])
                col_max[c] = max(col_max[c], answer[r][c])

        return answer

# Example walkthrough
matrix = [[1, 2], [3, 4]]
solution = Solution()
result = solution.matrixRankTransform(matrix)
print(result)

56300