首页 > 编程 > Java > 正文

一个菜鸟的java求字谜算法

2019-11-11 07:45:41
字体:
来源:转载
供稿:网友

《数据结构与算法分析》的一个课后习题

我自己写的代码如下。。。

感觉效率也太低了。。。

有大神能指导指导吗 可怜萌新路过

呃呃。。这是原题

编写一个程序求解字谜游戏问题

 1234
1this
2wats
3oahg
4fgdt
public class test02 {static String str [][] = {{"t","h","i","s"},{"w","a","t","s"},{"o","a","h","g"},{"f","g","d","t"}};public static void main(String args[]){int index[] = jiemi("this");jiemi01("this",index[0],index[1]);jiemi01("this",index[2],index[3]);}public static int[] jiemi(String s){int index[] = {0,0,0,0,0,0};int num = 0;char c[] = s.toCharArray();String first = c[0]+"";for(int i = 0;i<4;i++){for(int j = 0;j<4;j++){if(first.equals(str[i][j])){index[num++] = i ;index[num++] = j;}}}int t1 = index[0];int t2 = index[1];int t3 = index[2];int t4 = index[3];return index;}public static void jiemi01(String s,int a,int b){String temp = "";for(int j = b;j>=0;j--){temp+=str[a][j];}isornot(temp,s);temp = "";for(int i = a;i>=0;i--){temp+=str[i][b];}isornot(temp,s);temp="";for(int j = b;j<=3;j++){temp+=str[a][j];}isornot(temp,s);temp = "";for(int i = a;i<=3;i++){temp+=str[i][b];}isornot(temp,s);temp = "";int min = min(a,b);int max = max(a,b);int t = b;for(int i = min;i>=0;i--){temp+=str[i][t--];}isornot(temp,s);temp = "";t = a;for(int i = max;i<=3;i++){temp+=str[t--][i];}temp = "";t = a;for(int i = max;i<=3;i++){temp+=str[t++][i];}temp = "";t = a;for(int i = max;i>=0;i--){temp+=str[t++][i];}isornot(temp,s);}public static void isornot(String temp,String s){if(temp.equals(s)){System.out.PRintln(temp+"是字谜");System.exit(0);}}public static int min(int a,int b){if(a<b){return a;}if(a>b){return b;}else{return a;}}public static int max(int a,int b){if(a<b){return b;}if(a>b){return a;}else{return a;}}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表