<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]]:
        # get the list of positions for each distinct numeric value
        val_positions = defaultdict(list)
        for i, row in enumerate(matrix):
            for j, val in enumerate(row):
                val_positions[val].append((i, j))

        # for each numeric value, group all positions which are
        # connected either by the same row or the same column
        val_pos_groups = {}
        for val, pos_ls in val_positions.items():
            # groups is a dict of unique auto-incremented IDs to disjoint sets of positions, where members
            # of each set share at least a row or a column with at least one other member in the same set
            groups, gid = {}, 0

            # these dicts map the row and column indices of the current value to the index
            # of a positional group in the groups disjoint-sets list initialized above
            row2grp, col2grp = {}, {}

            for i, j in pos_ls:

                # the new position joins together two previously disjoint groups
                if i in row2grp and j in col2grp and row2grp[i] != col2grp[j]:

                    # determine which group gets merged into which based on their sizes
                    merger, merged = ((row2grp[i], col2grp[j])
                                      if len(groups[row2grp[i]]) >= len(groups[col2grp[j]]) else
                                      (col2grp[j], row2grp[i]))

                    # add the new position into the larger sized group
                    groups[merger].add((i, j))

                    # merge the smaller sized group into the larger group, then remove the merged group
                    groups[merger].update(groups[merged])
                    groups.pop(merged)

                    # update the row & col to group ID mappings accordingly by pointing rows/cols
                    # that directed to the merged group to the ID of the new parent merger group
                    for i, g in row2grp.items():
                        if g == merged: row2grp[i] = merger
                    for j, g in col2grp.items():
                        if g == merged: col2grp[j] = merger

                # add position to existing row group; and point the new column to the same group
                elif i in row2grp:
                    groups[row2grp[i]].add((i, j))
                    col2grp[j] = row2grp[i]

                # add position to existing column group; and point the new row to the same group
                elif j in col2grp:
                    groups[col2grp[j]].add((i, j))
                    row2grp[i] = col2grp[j]
                
                # the curr position shares no rows nor columns w/ previously seen
                # positions for this value; thus create a new set group for it
                else:
                    groups[gid] = {(i, j)}          # create new group set for the position
                    row2grp[i] = col2grp[j] = gid   # add entries in row & col to group mappings
                    gid += 1                        # auto-increment the next available group ID

            val_pos_groups[val] = list(groups.values())

        # with the above pre-processing completed, we can finally perform the rank transform
        res = [[0 for _ in row] for row in matrix]
        max_row_ranks, max_col_ranks = defaultdict(int), defaultdict(int)
        for pos_grp in (pg for _, groups in sorted(val_pos_groups.items()) for pg in groups):
            # determine the rank for the curr-numeric value based on already determined
            # ranks for all occurrences of the val that are in the curr positional group
            curr_rk = 0
            for i, j in pos_grp:
                curr_rk = max(curr_rk, max(max_row_ranks[i], max_col_ranks[j]) + 1)
            
            # set all occurrences of the curr value to this uniform rank
            for i, j in pos_grp:
                res[i][j] = max_row_ranks[i] = max_col_ranks[j] = curr_rk

        return res
90800