【面试】输出"蛇形"矩阵

一、题目描述

  腾讯实习在线笔试的一道题目。

  根据输入的数字(< 1000),输出这样的"蛇形"矩阵,如下。输入n,输出(n * n)阶矩阵,满足由外到内依次增大。

  如: 输入2,则输出如下矩阵

  1  2

  4  3

  输入3,则输出如下矩阵  

  1  2  3

  8  9  4

  7  6  5

  输入4,则输出如下矩阵

  1  2  3  4

  12  13  14  5  

  11  16  15  6  

  10  9  8  7

二、代码如下  

  思路:可以分成四大步,向右,向下,向左,向上。

import java.util.*;
/**
 * 输出"蛇形"矩阵
 * @author LEESF
 *
 */
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int no = scan.nextInt();
        scan.close();
        int[][] result = new int[no][no];
        int i = 1;
        // 第几次向右走
        int rightCount = 0;
        // 第几次向右走
        int downCount = 0;
        // 第几次向左走
        int leftCount = 0;
        // 第几次向上走
        int upCount = 0;
        while (i <= no * no) { // 总共走的步数
            // 向右走
            for (int right = rightCount; right < no - rightCount; right++) {
                if (i > no * no)
                    break;
                result[rightCount][right] = i;
                i++;
            }
            rightCount++;
            
            // 向下走
            for (int down = downCount + 1; down < no - downCount; down++) {
                if (i > no * no)
                    break;
                result[down][no - downCount - 1] = i;
                i++;
            }
            downCount++;
            
            // 向左走
            for (int left = no - leftCount - 1; left > leftCount; left--) {
                if (i > no * no)
                    break;
                result[no - leftCount - 1][left - 1] = i;
                i++;
            }
            leftCount++;
            
            // 向上走
            for (int up = no - upCount - 1; up > upCount + 1; up--) {
                if (i > no * no)
                    break;
                result[up - 1][upCount] = i;
                i++;
            }
            upCount++;
        }
        
        // 输出结果
        for (int j = 0; j < no; j++) {
            for (int k = 0; k < no; k++) {
                System.out.print(result[j][k] + " ");
            }
        }
    }
}
原文地址:https://www.cnblogs.com/leesf456/p/5350839.html