Java实现回形遍历的代码
分类:Java, Java语言
阅读 (1,751)
Add comments
10月 102017
本来以为这样的回形是有规律可循的,但是找了好长时间没找到,看来只能用遍历了。
x,y的使用有些乱,读者自己理一下吧
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 |
private String huiXingBianLi(){ final int FLAG_RIGHT = 0; final int FLAG_DOWN = 1; final int FLAG_LEFT = 2; final int FLAG_UP = 3; String resultStr = ""; int flag = FLAG_RIGHT; final int countx = 10; final int county = 11; int x = 0, y = 0; int minx = 0, maxx = county - 1, miny = 1, maxy = countx - 1; int[][] result = new int[countx][county]; int i = 0; while(i < countx * county){ result[y][x] = ++i; if(flag == FLAG_RIGHT){ if(x >= maxx){ maxx--; y++; flag = FLAG_DOWN; continue; }else{ x++; } } if(flag == FLAG_DOWN){ if(y >= maxy){ maxy--; x--; flag = FLAG_LEFT; continue; }else{ y++; } } if(flag == FLAG_LEFT){ if(x <= minx){ minx++; y--; flag = FLAG_UP; continue; }else{ x--; } } if(flag == FLAG_UP){ if(y <= miny){ miny++; x++; flag = FLAG_RIGHT; continue; }else{ y--; } } } resultStr = ""; for(int i1=0; i1 < countx ; i1++){ for(int j1 = 0; j1 < county ; j1++){ if(j1 == 0){ resultStr += String.format(" %03d", result[i1][j1]); }else { resultStr += "..." + String.format("%03d", result[i1][j1]); } } resultStr += "\n"; } return resultStr; } |
结果展示:
1 2 3 4 5 6 7 8 9 10 |
001...002...003...004...005...006...007...008...009...010...011 038...039...040...041...042...043...044...045...046...047...012 037...068...069...070...071...072...073...074...075...048...013 036...067...090...091...092...093...094...095...076...049...014 035...066...089...104...105...106...107...096...077...050...015 034...065...088...103...110...109...108...097...078...051...016 033...064...087...102...101...100...099...098...079...052...017 032...063...086...085...084...083...082...081...080...053...018 031...062...061...060...059...058...057...056...055...054...019 030...029...028...027...026...025...024...023...022...021...020 |