Java 8,1045字节
高尔夫球
staticchar[][]a={{'A','B','C','D','E','F','G'},{'H','I','J','K','L','M','N'},{'O','P','Q','R','S','T','U'},{'V','W','X','Y','Z','.',''}};staticintm=Integer.MAX_VALUE;staticStringn="";staticboolean[][]c(boolean[][]a){boolean[][]r=newboolean[4][];for(inti=0;i<4;i)r[i]=a[i].clone();returnr;}staticvoidg(inti,intj,boolean[][]v,chard,Stringp){v[i][j]=true;if(a[i][j]==d&&p.length()<m){m=p.length();n=p;}if(i-1<0){if(!v[3][j])g(3,j,c(v),d,p"^");}elseif(!v[i-1][j])g(i-1,j,c(v),d,p"^");if(i1>3){if(!v[0][j])g(0,j,c(v),d,p"v");}elseif(!v[i1][j])g(i1,j,c(v),d,p"v");if(j-1<0){if(!v[i][6])g(i,6,c(v),d,p"<");}elseif(!v[i][j-1])g(i,j-1,c(v),d,p"<");if(j1>6){if(!v[i][0])g(i,0,c(v),d,p">");}elseif(!v[i][j1])g(i,j1,c(v),d,p">");}publicstaticvoidmain(String[]args){boolean[][]v=newboolean[4][7];Scannerx=newScanner(System.in);Strings=x.next();Stringpath="";intp=0;intq=0;for(inti=0;i<s.length();i){chart=s.charAt(i);g(p,q,c(v),t,"");path=n".";n="";m=Integer.MAX_VALUE;for(intj=0;j<4;j){for(intk=0;k<7;k){if(a[j][k]==t){p=j;q=k;}}}}System.out.println(path);}
可读的
static char[][] a = {
{'A','B','C','D','E','F','G'},
{'H','I','J','K','L','M','N'},
{'O','P','Q','R','S','T','U'},
{'V','W','X','Y','Z','.',' '}
};
static int m = Integer.MAX_VALUE;
static String n="";
static boolean[][] c(boolean[][] a){
boolean [][] r = new boolean[4][];
for(int i = 0; i < 4; i++)
r[i] = a[i].clone();
return r;
}
static void g(int i, int j,boolean[][] v,char d,String p) {
v[i][j] = true;
if (a[i][j]==d && p.length()<m){
m=p.length();
n=p;
}
if (i-1<0) {
if(!v[3][j])
g(3, j, c(v), d, p + "^");
}
else if (!v[i-1][j])
g(i-1, j, c(v), d, p + "^");
if (i+1>3) {
if(!v[0][j])
g(0, j, c(v), d, p + "v");
}
else if(!v[i+1][j])
g(i+1, j, c(v), d, p + "v");
if (j-1<0) {
if(!v[i][6])
g(i, 6, c(v), d, p + "<");
}
else if (!v[i][j-1])
g(i, j-1, c(v), d, p + "<");
if (j+1>6) {
if (!v[i][0])
g(i, 0, c(v), d, p + ">");
}
else if (!v[i][j+1])
g(i, j+1, c(v), d, p + ">");
}
public static void main(String[] args) {
boolean[][] v = new boolean[4][7];
Scanner x = new Scanner(System.in);
String s = x.next();
String path="";
int p=0;
int q=0;
for(int i=0;i<s.length();i++){
char t=s.charAt(i);
g(p,q,c(v),t,"");
path+=n+".";
n="";
m=Integer.MAX_VALUE;
for(int j=0;j<4;j++){
for(int k=0;k<7;k++){
if(a[j][k]==t) {
p=j;
q=k;
}
}
}
}
System.out.println(path);
}
说明
解决方案是直接的方法:优化的蛮力不佳。该方法g(...)
是遍历每个排列(上,下,左,右)的基本深度优先搜索。在对测试用例进行排序时进行了一些细微的修改,我得到了输出:
<<.v<.v<<<.v<<<.^.^<<.^<.
v<<.v>>.v>>>.^^>.^.^<<.
<<.<..^^<.>.>>.^<.
v<<.^<.>>.^^>.
.^<.v>>>.<<.^^<<.
>.^^<.^^>.
^<.
// new line for the last