黑马程序员技术交流社区

标题: 写一方法,打印等长的二维数组,要求从1开始的自然数由... [打印本页]

作者: 小蔡@¥¥¥    时间: 2016-8-26 21:55
标题: 写一方法,打印等长的二维数组,要求从1开始的自然数由...
写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。当n=4时;
1        2        3        4
12        13        14        5
11        16        15        6
10        9        8        7


作者: ancheng    时间: 2016-8-28 08:46
[Java] 纯文本查看 复制代码
import java.util.Scanner;
/**
*
* @author AnCheng
*
*/
public class Main {

        public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                int m = sc.nextInt();
                int n = sc.nextInt();
                int[][] arr = new int[m][n];
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                arr[j] = sc.nextInt();
                        }
                }
                sc.close();
                spiralOrderPrint(arr);
        }

        public static void spiralOrderPrint(int[][] m) {
                int r = 0;
                int c = 0;
                int tR = 0;
                int tC = 0;
                int dR = m.length - 1;
                int dC = m[0].length - 1;
                int n = m.length * m[0].length;
                for (int count = 0; count < n; tR++, tC++, dR--, dC--) {
                        while (r < dR && count <= n) {
                                System.out.print(m[r++][c] + " ");
                                count++;
                        }
                        while (c < dC && count < n) {
                                System.out.print(m[r][c++] + " ");
                                count++;
                        }
                        while (r > tR && count < n) {
                                System.out.print(m[r--][c] + " ");
                                count++;
                        }
                        while (c > tC && count < n) {
                                System.out.print(m[r][c--] + " ");
                                count++;
                        }
                        c++;
                        r++;
                }
        }

}





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