<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

class DSU:
    def __init__(self, m, n):
        self.m = m
        self.n = n
        self.set = list(range(n*m))
        self.size = [1 for _ in range(n*m)]

    def linCoord(self, coord: tuple[int, int]):
        return coord[0]*self.n + coord[1]

    def coordLin(self, lin: int):
        return (lin // self.n, lin % self.n)

    def find(self, coord: tuple[int, int]) -> int:
        lin = self.linCoord(coord)
        if self.set[lin] != lin:
            self.set[lin] = self.find(self.coordLin(self.set[lin]))
        return self.set[lin]
        
    def join(self, coord1: tuple[int, int], coord2: tuple[int, int]):
        s1 = self.find(coord1)
        s2 = self.find(coord2)
        if self.size[s1] < self.size[s2]:
            s1, s2 = s2, s1

        self.set[s2] = s1
        self.size[s1] += self.size[s2]

class Solution:
    def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:
        m, n = len(matrix), len(matrix[0])
        dsu = DSU(m, n)

        for i in range(m):
            l = list(enumerate(matrix[i]))
            l.sort(key=lambda x: x[1])
            for j in range(1, n):
                if l[j][1] == l[j-1][1]:
                    dsu.join((i, l[j][0]), (i, l[j-1][0]))
        for j in range(n):
            l = [(i, matrix[i][j]) for i in range(m)]
            l.sort(key=lambda x: x[1])
            for i in range(1, m):
                if l[i][1] == l[i-1][1]:
                    dsu.join((l[i][0], j), (l[i-1][0], j))





        # for i in range(m):
        #     for j in range(n):
        #         for k in range(i+1, m):
        #             # vertical
        #             if matrix[i][j] == matrix[k][j]:
        #                 dsu.join((i, j), (k, j))
        #         for k in range(j+1, n):
        #             # horizontal
        #             if matrix[i][j] == matrix[i][k]:
        #                 dsu.join((i, j), (i, k))


        adj = defaultdict(list)
        for i in range(m):
            l = list(enumerate(matrix[i]))
            l.sort(key=lambda x: x[1], reverse=True)
            for j in range(1, n):
                if l[j][1] != l[j-1][1]:
                    adj[dsu.find((i, l[j][0]))].append(dsu.find((i, l[j-1][0])))
        for j in range(n):
            l = [(i, matrix[i][j]) for i in range(m)]
            l.sort(key=lambda x: x[1], reverse=True)
            for i in range(1, m):
                if l[i][1] != l[i-1][1]:
                    adj[dsu.find((l[i][0], j))].append(dsu.find((l[i-1][0], j)))


        # adj = defaultdict(list)
        # for i in range(m):
        #     for j in range(n):
        #         for k in range(m):
        #             # vertical
        #             if matrix[i][j] < matrix[k][j]:
        #                 adj[dsu.find((i, j))].append(dsu.find((k, j)))
        #         for k in range(n):
        #             # horizontal
        #             if matrix[i][j] < matrix[i][k]:
        #                 adj[dsu.find((i, j))].append(dsu.find((i, k)))

        def getMatrixVal(lin: int):
            i, j = dsu.coordLin(lin)
            return matrix[i][j]

        topo = list(adj.items())
        topo.sort(key=lambda x: getMatrixVal(x[0]))

        valueToSet = defaultdict(lambda: 1)
        for setId, adjList in topo:
            for neigh in adjList:
                valueToSet[neigh] = max(valueToSet[neigh], valueToSet[setId] + 1)
        
        return [[valueToSet[dsu.find((i, j))] for j in range(n)] for i in range(m)]
                

46900