I have an n x n matrix which I need to convert into a list sorted by value. Starting with the maximum value cell at (row x1, col y1), I must immediately exclude all cells where (x >= x1, y <= y1) or (x <= x1, y >= y1).
There are n x n cells, and each of them is getting compared to (n - x1) * y1 + x * (n - y1) cells. This gives an overall time complexity of O(n^4) and is making my algorithm very slow. Can you improve the scalability of this algorithm?
Here's a visualisation:
Here's some python/pseudocode:
INVALID = -1
class Pair:
def __init__(self, x, y, value):
self.x = x
self.y = y
self.value = value
def get_ordered_pairs(matrix):
pairs = []
for i in range(len(matrix) * len(matrix[0])):
pairs.append(get_max_pair(matrix))
return pairs
def get_max_pair(matrix):
max_pair = Pair(INVALID, INVALID, INVALID)
for x in range(len(matrix)):
for y in range(len(matrix[x])):
if matrix[x][y] > max_pair.value:
max_pair = Pair(x, y, matrix[x][y])
# invalidate entire row
for y in range(len(matrix[0])):
matrix[max_pair.x][y] = INVALID
# invalidate entire column
for x in range(len(matrix)):
matrix[x][max_pair.y] = INVALID
# invalidate top right
for x in range(max_pair.x + 1, len(matrix)):
for y in range(max_pair.y):
matrix[x][y] = INVALID
# invalidate bottom left
for y in range(max_pair.y + 1, len(matrix[0])):
for x in range(max_pair.x):
matrix[x][y] = INVALID
return max_pair

