Java编码 蛇形矩阵的构建与遍历输出
一、蛇形矩阵的构建,并按行输出
例:
输入:n,
生成n*n的蛇形矩阵
1 2 3
8 9 4
7 6 5
输出:1 2 3 8 9 4 7 6 5
java编码
public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); if(n < 0) return; if(n == 1){ System.out.println(1); return; } int[][] m = new int[n][n]; //定义4个变量,分别记录当前行和列的上下限 int i1 = 0, j1 = 0, i2 = n - 1, j2 = n - 1; int i = 0, j = 0; int begin = 1; //4个for循环,遍历蛇形矩阵 while(i1 <= i2 && j1 <= j2){ for(; j <= j2; ++j){//one row m[i][j] = begin; begin++; } j--; i++; i1++; for(; i <= i2; ++i){//one column m[i][j] = begin; begin++; } j2--; j--; i--; for(; j >= j1; --j){//one row m[i][j] = begin; begin++; } i2--; j++; i--; for(; i >= i1; --i){//one column m[i][j] = begin; begin++; } j1++; j++; i++; } //按行输出 蛇形矩阵 for(i = 0; i < n; ++i) for(j = 0; j < n; ++j) System.out.println(m[i][j] + " "); }
二、已知蛇形矩阵m,顺时针顺序输出
例:
矩阵m
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
输出:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public static void main(String[] args) { // TODO Auto-generated method stub int[][] m = {{1,2,3,4},{12,13,14,5},{11,16,15,6},{10,9,8,7}}; int n = m.length; int c = m[0].length; if(n == 1){ for(int a = 0; a < m[0].length; ++a) System.out.print(m[0][a] + " "); } if(c == 1){ for(int a = 0; a < m.length; ++a) System.out.print(m[a][0] + " "); } //定义4个指针,记录行和列的上下限 int i1 = 0, j1 = 0, i2 = n - 1,j2 = c - 1; int i = 0, j = 0; while(i1 <= i2 && j1 <= j2){//one row for(; j <= j2; ++j) System.out.print(m[i][j] + " "); i++; j--; i1++; for(; i <= i2; ++i)//one column System.out.print(m[i][j] + " "); i--; j--; j2--; for(; j >= j1; --j)//one row System.out.print(m[i][j] + " "); i--; j++; i2--; for(; i >= i1; --i)//one column System.out.print(m[i][j] + " "); i++; j++; j1++; } }