首页 > 代码库 > 蛇形矩阵

蛇形矩阵

 1 /** 2  * 蛇形矩阵 3  *  4  * @author jinfeng 5  *  6  */ 7 public class SnakeMatrix { 8  9     /**10      * 输入一个整数n,返回填充数据后的蛇形矩阵,其实,所有的算法都可以看成数学题来做11      * 12      * @param n13      */14     public static int[][] getSnakeMatrix(int n) {15         int[][] matrix = new int[n][n];16 17         int count = 1;18         int i, j;19 20         // 输出上三角21         for (int k = 0; k < n; ++k)22             // 当下标之和为偶数时23             if (k % 2 == 0) {24                 i = 0;25                 j = k;26                 for (; i <= k; ++i, --j)27                     matrix[i][j] = count++;28             // 当下标之和为奇数时29             } else {30                 i = k;31                 j = 0;32                 for (; j <= k; ++j, --i)33                     matrix[i][j] = count++;34             }35 36         // 输出下三角37         for (int k = n, index = 1; k <= 2 * n - 2; ++k, ++index)38             // 当下标之和为偶数时39             if (k % 2 == 0) {40                 i = index;41                 j = k - index;42                 for (; i <= k - index; ++i, --j)43                     matrix[i][j] = count++;44             // 当下标之和为奇数时45             } else {46                 j = index;47                 i = k - index;48                 for (; j <= k - index; ++j, --i)49                     matrix[i][j] = count++;50             }51         52         return matrix;53     }54 55     public static void main(String[] args) {56 57         int[][] matrix = getSnakeMatrix(10);58         for (int i = 0; i < matrix.length; ++i) {59             for (int j = 0; j < matrix[0].length; ++j)60                 System.out.print(matrix[i][j] + "\t");61             System.out.println();62         }63     }64 65 }

 

蛇形矩阵