赛码模拟题:蛇形填数 SnakeSquare (Java 8)

发布时间:2019-11-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了赛码模拟题:蛇形填数 SnakeSquare (Java 8)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

题目:
在nn方阵里填入1,2,...,nn,要求填成蛇形。例如n=4时方阵为:

10 11 12 1 9  16 13 2 8  15 14 3 7  6  5  4 

解法:
这题感觉挺麻烦的,要对整个矩阵的形成过程有清晰的认识。

snake width =

填数的循环按照Step1->Step2->SteP3->Step4走。重点是控制蛇的方向和移动范围。

我用了一个布尔控制蛇垂直走还是水平走,
另外一个布尔控制在当前方向递增递减,
另外用四个变量控制蛇上下左右活动范围。

假设j表示行数,i表示列数:
S1: 垂直向下,j递增,i不变,到达最下方变水平,递增变为递减。
S2: 水平向左,j不变,i递减,到达最左方变垂直,递减还是递减。
S3:垂直向上, j递减,i不变,到达最上方变水平,递减变递增。
S4: 水平向右,j不变,i递增,到达(最右-1)列时变垂直进入下一个内环,递增还是递增。

尤其要注意分清行数列数和水平垂直方向的关系:水平走是列数变,垂直走是行数变。

还有要注意矩阵下标和x,y坐标的区别,原点位置不同,不建议用x,y作为变量名,易混淆。


代码:

import java.util.*;  public class Main {      private static void snakeSquare(int n) {         int[][] square = new int[n][n];         // true is increment, false is decrement         boolean delta = true;          // ture is going through row j(vertically), false is going through column i (horizontally)         boolean direction = true;         // R,r是上下边界值;C,c是左右边界值         int R = n-1, C = n-1, r = 0, c = 0;         for(int i = n-1, j = 0,counter = 0 ; counter < n*n;counter++){             square[j][i] = counter + 1;             // 垂直往下             if(direction && delta) {                 j+=1;                 if(j == C) {direction = !direction;delta = !delta;}              }             //垂直向上             else if(direction && !delta) {                 j -= 1;                 if(j == c) {direction = !direction;delta = !delta;}             }             //水平向右             else if(!direction && delta) {                 i += 1;                 if(i == R-1) {                     direction = !direction;                     //水平向右结束后说明要进入下一个内环,要改变边界范围                     C -= 1;R -= 1;r += 1;c += 1;                 }             }             //水平向左             else {                 i -= 1;                 if(i == r)                     direction = !direction;             }         }          for(int i = 0 ; i < n; i++){             for(int j = 0; j < n;j++)                 System.out.print(square[i][j] + " ");             System.out.printf("%n");         }      }      public static void main(String[] args) {     // wrITe your code here         Scanner scn = new Scanner(System.in);         while(scn.hasNextInt())             snakeSquare(scn.nextInt());         scn.close();     } } 

脚本宝典总结

以上是脚本宝典为你收集整理的赛码模拟题:蛇形填数 SnakeSquare (Java 8)全部内容,希望文章能够帮你解决赛码模拟题:蛇形填数 SnakeSquare (Java 8)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。