, O (NM log (NM)).
:
, (a,b) (c,d) G(a,b,c,d). , , G. , , (i,j), G(i,b,c,j) G(a,j,i,d) min ( ). . ? , , G(a,b,c,d) ( (i,j)). (i,j), , , .

, min G(1,1,m,n). , (i,j). . min G(1,1,i,j) G(i,j,m,n) . , m+n-1 , . G(1,1,m,n) , .
:
G . , ? - Dict, (i,j), (i,j). , .
, . G(1,1,m,n).
S.
, T(G), G(a,b,c,d) in T, G.left = G(a,b,i,j) G.right = G(i,j,c,d), (i,j) = location of min val in G(a,b,c,d)
:
for each val in sorted key set S do
(i,j) <- Dict(val)
Grid G <- Root(T)
do while (i,j) in G
if G has no child do
G.left <- G(a,b,i,j)
G.right <- G(i,j,c,d)
else if (i,j) in G.left
G <- G.left
else if (i,j) in G.right
G <- G.right
else
dict(val) <- null
end do
end if-else
end do
end for
for each val in G(1,1,m,n)
if dict(val) not null
solution.append(val)
end if
end for
return solution
Java:
class Grid{
int a, b, c, d;
Grid left, right;
Grid(int a, int b, int c, int d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
left = right = null;
}
public boolean isInGrid(int e, int f){
return (e >= a && e <= c && f >= b && f <= d);
}
public boolean hasNoChild(){
return (left == null && right == null);
}
}
public static int[] findPath(int[][] arr){
int row = arr.length;
int col = arr[0].length;
int[][] index = new int[row*col+1][2];
HashMap<Integer,Point> map = new HashMap<Integer,Point>();
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
map.put(arr[i][j], new Point(i,j));
}
}
Grid root = new Grid(0,0,row-1,col-1);
SortedSet<Integer> keys = new TreeSet<Integer>(map.keySet());
for(Integer entry : keys){
Grid temp = root;
int x = map.get(entry).x, y = map.get(entry).y;
while(temp.isInGrid(x, y)){
if(temp.hasNoChild()){
temp.left = new Grid(temp.a,temp.b,x, y);
temp.right = new Grid(x, y,temp.c,temp.d);
break;
}
if(temp.left.isInGrid(x, y)){
temp = temp.left;
}
else if(temp.right.isInGrid(x, y)){
temp = temp.right;
}
else{
map.get(entry).x = -1;
break;
}
}
}
int[] solution = new int[row+col-1];
int count = 0;
for(int i = 0 ; i < row; i++){
for(int j = 0; j < col; j++){
if(map.get(arr[i][j]).x >= 0){
solution[count++] = arr[i][j];
}
}
}
return solution;
}
- O(NM) - O(N+M). : O(NM)
, - O(NM log(NM)); NM - O(NM log(N+M)). - O(NM log(NM)).
, , , (i,j) , .
FYI: , , , - , , 1 to NM. O(NM log(N+M)), ( .)