笔试题:蛇形矩阵
n = 2时
[1, 2]
[4, 3]
n = 3 时
[1, 2, 3]
[8, 9, 4]
[7, 6, 5]
n = 4 时
[1,   2,    3,   4, 5]
[16, 17, 18, 19, 6]
[15, 24, 25, 20, 7]
[14, 23, 22, 21, 8]
[13, 12, 11, 10, 9]
思路:先打印最外层一圈,缩小问题,再打印内层一圈,依此类推
package test5; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num = scan.nextInt(); int[][] res = new int[num][num]; int row = 0; int col = 0; int count = 1; int end = num; int i = row; int j = col; while (count <= num * num) { // 打印最上一行 for (i = row, j = col; j < end; j++) { res[i][j] = count++; } // //打印最右一列 for (i = i + 1, j = j - 1; i < end; i++) { res[i][j] = count++; } // //打印最下一行 for (j = j - 1, i = i - 1; j >= (num - end); j--) { res[i][j] = count++; } // //打印最左一列 for (i = i - 1, j = j + 1; i > (num - end); i--) { res[i][j] = count++; } //行列增1 row ++; col ++; end --; } for (int k = 0; k < num; k++) { System.out.println(Arrays.toString(res[k])); } } }
    http://www.cnblogs.com/makexu/

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号