📅  最后修改于: 2023-12-03 15:12:36.400000             🧑  作者: Mango
This is a description of Problem 6 from the CS stream of GATE 2013.
There is given an m x n matrix A. Consider a directed graph where each cell of the matrix is a node and there is a directed edge from a node (i, j) to (i', j') if and only if A[i'][j'] > A[i][j]. A node is a sink if it has no outgoing edges. Find all the sinks in the graph.
The solution to this problem can be obtained using a modified Depth-First Search (DFS) algorithm. Firstly, we create an adjacency matrix representation of the directed graph representing each cell of the matrix as a node and a directed edge between two nodes (i, j) and (i', j') if and only if A[i'][j'] > A[i][j]. Next, we traverse the graph using DFS starting from each node in the matrix. If a node is a sink, we add it to the list of sinks. The DFS algorithm is modified as follows:
The time complexity of the above algorithm is O(mn) and space complexity is O(mn).
Here's a code implementation in Python:
def get_sinks(matrix):
m, n = len(matrix), len(matrix[0])
visited = [[False] * n for _ in range(m)]
sinks = []
def dfs(i, j):
visited[i][j] = True
for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
if 0 <= x < m and 0 <= y < n and not visited[x][y] and matrix[x][y] <= matrix[i][j]:
dfs(x, y)
if all([matrix[x][y] <= matrix[i][j] for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)] if 0 <= x < m and 0 <= y < n]):
sinks.append((i, j))
for i in range(m):
for j in range(n):
if not visited[i][j]:
dfs(i, j)
return sinks
The above implementation creates an m x n
matrix called visited
to keep track of visited nodes during DFS. The dfs
function is defined inside the get_sinks
function and takes two arguments i
and j
representing the row and column indices of the current node. The out-neighbours of the current node are checked recursively using DFS and if the current node is a sink, it is appended to the sinks
list. The get_sinks
function then returns the sinks
list. The time complexity of this implementation is O(mn) and space complexity is also O(mn).
In this problem, we saw how to use a modified DFS algorithm to find all the sinks in a matrix represented as a directed graph. The solution is efficient with a time complexity of O(mn) and space complexity of O(mn).