黑马程序员技术交流社区

标题: 螺旋矩阵最好理解的代码 [打印本页]

作者: 青春随了风    时间: 2015-8-26 13:32
标题: 螺旋矩阵最好理解的代码
关于输出螺旋矩阵这个问题,相信大家都有所了解,课堂上老师也给的那个代码,很多人说理解起来有点困难,下面发一个我觉得更好理解的一个代码
作者: 青春随了风    时间: 2015-8-26 13:38
/**
* 打印螺旋数组 如:
* 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
*/
public class LuoXuanJuZhen {
        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                int len = sc.nextInt();
                print(len);
        }

        private static void print(int len) {
                int levels = len / 2 + len % 2;
                int x = 0;
                int y = 0;
                int i = 0;
                int count = 1;
                int[][] arr = new int[len][len];
                while (i < levels) {
                       
                        //打印第一行的数,以5X5的矩阵为例,第一次循环输出1 2 3 4 5
                        for (; y < len - i; y++) {
                                arr[x][y] = count;
                                count++;
                        }
                        y--;
                        x++;
                       
                        //打印最后一列的数6 7 8 9
                        for (; x < len - i; x++) {
                                arr[x][y] = count;
                                count++;
                        }
                        x--;
                        y--;
                       
                        //打印最后一行的数10 11 12 13
                        for (; y >= i; y--) {
                                arr[x][y] = count++;
                        }
                        y++;
                        x--;
                       
                        //打印第一列的数14 15 16
                        for (; x > i; x--) {
                                arr[x][y] = count++;
                        }
                        x++;
                        y++;
                        i++;
                }
                for (int m = 0; m < len; m++) {
                        for (int n = 0; n < len; n++) {
                                System.out.print(arr[m][n] + "\t");
                        }
                        System.out.println();
                }
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2