java实现对给定维数矩阵按顺时针螺旋循环递增实现矩阵的赋值

package array;

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input=new Scanner(System.in);
        //输入数组矩阵的维数(注释以4编写)
        int n=input.nextInt();
        //初始化创建起整个数组矩阵
        int array[][]=new int[n][n];
        /*
         * 2019.3.6
         * currRow是切换循环时的行 顺序依次是0 3 1 2规律是+3  -2  +1
         * currCol是切换循环时的列 顺序依次是3 0 2 1规律是-3  +2  -1
         * temp是用作修改currRow的变量
         * temp1是用作修改currCol的变量
         * start是每一圈循环是的起始位置
         * store1是存储数组矩阵的维数
         */
        int currRow=0,store=1,currCol=n-1;
        int temp=1;
        int temp1=1;
        int start=0;
        int store1=n;
        /*
         * 主要思想就是对于矩阵的最外面的4个边单独写一个循环
         * 对于里面的部分可以看做是一个缩小的矩阵,只需要在while循环最后修改循环开始和结束的变量(start和n)
         */
        while(store<=(store1*store1)) {
            //System.out.println("执行到此");
            for(int i=start;i<n;i++) {
                array[currRow][i]=store++;
            }
            currRow+=store1-temp;
            temp++;
            for(int i=start+1;i<n-1;i++) {
                array[i][currCol]=store++;
            }
            currCol-=store1-temp1;
            temp1++;
            for(int i=n-1;i>start;i--) {
                array[currRow][i]=store++;
            }
            currRow-=store1-temp;
            temp++;
            for(int i=n-1;i>start;i--) {
                array[i][currCol]=store++;
            }
            currCol+=store1-temp1;
            temp1++;
            n-=1;
            start++;
        }
        for(int i=0;i<store1;i++) {
            for(int t:array[i]) {
                System.out.print(t+"   ");
            }
            System.out.println();
        }
        
    }

}
 

猜你喜欢

转载自blog.csdn.net/Is_ever/article/details/88246069
今日推荐