- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexicoSmallestPath.java
More file actions
Latest commit
112 lines (103 loc) · 2.62 KB
/
Copy pathLexicoSmallestPath.java
File metadata and controls
112 lines (103 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
//http://stackoverflow.com/questions/29376069/lexographically-smallest-path-in-a-nm-grid/39692211#39692211
importjava.awt.Point;
importjava.util.Arrays;
importjava.util.HashMap;
importjava.util.SortedSet;
importjava.util.TreeSet;
classRange{
inta, b, c, d;
Rangeleft, right;
Range(inta, intb, intc, intd){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
left = right = null;
}
publicbooleanisInRange(inte, intf){
return (e >= a && e <= c && f >= b && f <= d);
}
publicbooleanhasNoChild(){
return (left == null && right == null);
}
}
publicclassSolution{
publicstaticvoidmain(Stringargs[]){
int[][] arr = {
{6,18,13,11,2},
{20,19,24,10,5},
{25,12,1,17,9},
{8,23,4,21,22},
{3,15,16,14,7},
};
int[][] arr2 = {{4,3},{5,1}};
System.out.println(Arrays.toString(shortestPath(arr)));
}
publicstaticint[] shortestPath(int[][] arr){
introw = arr.length;
intcol = arr[0].length;
int[][] index = newint[row*col+1][2];
//HashMap<Integer,Point> map = new HashMap<Integer,Point>();
for(inti = 0; i < row; i++){
for(intj = 0; j < col; j++){
index[arr[i][j]][0]=i;
index[arr[i][j]][1]=j;
//map.put(arr[i][j], new Point(i,j));
}
}
Rangeroot = newRange(0,0,row-1,col-1);
for(inti = 1; i < index.length; i++){
//SortedSet<Integer> keys = new TreeSet<Integer>(map.keySet());
//for(Integer entry : keys){
Rangetemp = root;
while(temp.isInRange(index[i][0], index[i][1])){
if(temp.hasNoChild()){
temp.left = newRange(temp.a,temp.b,index[i][0], index[i][1]);
temp.right = newRange(index[i][0], index[i][1],temp.c,temp.d);
break;
}
if(temp.left.isInRange(index[i][0], index[i][1])){
temp = temp.left;
}
elseif(temp.right.isInRange(index[i][0], index[i][1])){
temp = temp.right;
}
else{
index[i][0] = -1;
break;
}
}
//int x = map.get(entry).x, y = map.get(entry).y;
intx = index[i][0], y = index[i][1];
while(temp.isInRange(x, y)){
if(temp.hasNoChild()){
temp.left = newRange(temp.a,temp.b,x, y);
temp.right = newRange(x, y,temp.c,temp.d);
break;
}
if(temp.left.isInRange(x, y)){
temp = temp.left;
}
elseif(temp.right.isInRange(x, y)){
temp = temp.right;
}
else{
//map.get(entry).x = -1;
index[i][0]=-1;
break;
}
}
}
int[] solution = newint[row+col-1];
intcount = 0;
for(inti = 0 ; i < row; i++){
for(intj = 0; j < col; j++){
if(index[arr[i][j]][0] >= 0){
//if(map.get(arr[i][j]).x >= 0){
solution[count++] = arr[i][j];
}
}
}
returnsolution;
}
}