我只會土法煉鋼,時間複雜度直接O(m^2)
有人能給一下策略嗎
我原本的代碼:
package a;
import java.util.*;
public class i401 {
public static void main(String [] args) {
Scanner sc=new Scanner(System.in);
List<sign>map=new ArrayList<>();
map.add(new sign(0,0,0));
int n=sc.nextInt();
sc.nextLine();
for(int i=0;i<n;i++) {
String[]s=sc.nextLine().split(" ");
map.add(new sign(Integer.parseInt(s[0]),Integer.parseInt(s[1]),Integer.parseInt(s[2])));
}
int lastway=1;
sign nows=map.get(0);
int time=0;
while(nows!=null) {
time++;
if(nows.go==0) {
switch(lastway) {
case(1):lastway=2;break;
case(2):lastway=1;break;
case(3):lastway=4;break;
case(4):lastway=3;break;
}
}
else {
switch(lastway) {
case(1):lastway=4;break;
case(2):lastway=3;break;
case(3):lastway=2;break;
case(4):lastway=1;break;
}
}
sign temp=null;
int close=Integer.MAX_VALUE;
switch(lastway) {
case(1):
for(sign e:map) {
if(e.x==nows.x&&e.y>nows.y&&close>Math.abs(nows.y-e.y)) {
close=Math.abs(nows.y-e.y);
temp=e;
}
}
break;
case(2):
for(sign e:map) {
if(e.y==nows.y&&e.x>nows.x&&close>Math.abs(nows.x-e.x)) {
close=Math.abs(nows.x-e.x);
temp=e;
}
}
break;
case(3):
for(sign e:map) {
if(e.x==nows.x&&e.y<nows.y&&close>Math.abs(nows.y-e.y)) {
close=Math.abs(nows.y-e.y);
temp=e;
}
}
break;
case(4):
for(sign e:map) {
if(e.y==nows.y&&e.x<nows.x&&close>Math.abs(nows.x-e.x)) {
close=Math.abs(nows.x-e.x);
temp=e;
}
}
break;
}
nows=temp;
}
System.out.println(time);
sc.close();
}
}
class sign {
int x;
int y;
int go;
public sign(int x,int y,int go) {
this.x=x;
this.y=y;
this.go=go;
}
}