Two different kinds of serpentine matrices are implemented through Java.
之前在一个面试题上看到了一个关于写出一个蛇形矩阵的问题,当时很是纠结,后来分析了一下之后,就觉的问题不是那么的难了。目前我见过的蛇形矩阵的考法有两种,一种是对角线式的蛇形矩阵,另一种是回旋绕的蛇形矩阵:**1 3 4 10** **2 5 9** 11 **6 8** 12 15 **7** 13 14 16对于对角线的类型来说,是比较简单的。1.首先我们可以观察数字从小到大的变化,会发现其实角标的变化分别是。0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 2 3 3 0 3 1 3 2 3 3 就会发现前一个角标的变化规律是0 |1,0| 2,1,0 |3,2,1,0| 后一个角标的变化是 0 |0,1|0,1,2|0,1,2,3| 这个时候,在蛇转换方向的是时候,我们还需要调整一下递增和递减的关系!!! 于是,规律就来了。我们可以先写出一个三角形,然后在写另一个三角形,是不是就会容易的很多!!!
Boolean flag=ture;//defines a flag bit. for(intE=0; E<arr.length; e++) {if(flag) { for(intc = e,d=0; c>=0&& d<=e;c--, d++) {///two digital edge increment and decrement of the corner markARR[C][D] = k++; } flag =!flag;//Adjust the direction, change the angle label to achieve the inverse direction of the numerical increase process!}Else{ for(intc = e,d=0; c>=0&& d<=e;c--, d++) {arr[d][c] = k++; } flag =!flag; }
于是我们就能够实现以个三角形的矩阵了!!**1 3 4 10** **2 5 9** 0 **6 8** 0 0 **7** 0 0 0那么,另一个三角形用和上面相反的思路就可以了!!!下面是完整的程序的代码:
PackageSamsung.kangjian.test;/** * Serpentine Matrix * @author Jiankang * */ Public class snakearray { Static BooleanFlag =true;Static intK =1; Public Static void Main(string[] args) {Snake1 (4); } Public Static void Snake1(intx) {intArr[][] =New int[x] [x];//Positive triangle input for(intE=0; e<arr.length; e++) {if(flag) { for(intc = e,d=0; c>=0&& d<=e;c--, d++) {arr[c][d] = k++; } flag =!flag; }Else{ for(intc = e,d=0; c>=0&& d<=e;c--, d++) {arr[d][c] = k++; } flag =!flag; } }//inverted triangle input. for(intg =1; g<arr.length;g++) {if(flag) { for(intH = g,i=arr.length-1; H<arr.length && i>0; h++,i--) {arr[i][h] = k++; } flag=!flag; }Else{ for(intH = g,i=arr.length-1; H<arr.length && i>0; h++,i--) {arr[h][i] = k++; } flag=!flag; } } for(intA =0; a<arr.length;a++) { for(intb=0; b<arr.length;b++) {System.out.print (arr[b][a]+" "); } System.out.println (""); } }}
The realization of the Serpentine matrix