zoukankan      html  css  js  c++  java
  • leetcode刷题21

    今天刷的题是LeetCode第59题,https://leetcode-cn.com/problems/spiral-matrix-ii/,该题的要求是:

    给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。比如:

    输入: 3
    输出:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]
    这个代码也很好写,我用的就是简单的while循环,具体地如下:
    public class GenerateMatrix_59_middle {
        public static void main(String[] args) {
            generate(5);
        }
        public static int[][] generate(int n){
            int[][] result=new int[n][n];//输出最后的结果
            boolean[][] hasNumber=new boolean[n][n];//判断这个位置上是否已经有的元素
            int i=1;
            int x=0;
            int y=0;
            while (i<=n*n){
                if (hasNumber[x][y]==false){
                    result[x][y]=i;
                    hasNumber[x][y]=true;
                    i++;
                }else {
                    if (y+1<n&&hasNumber[x][y+1]==false)y=y+1;
                    else if (x+1<n&&hasNumber[x][y+1]==false)x=x+1;
                    else if (y-1>=0&&hasNumber[x][y+1]==false)y=y-1;
                    else if (x-1>=0&&hasNumber[x][y+1]==false)x=x-1;
                    result[x][y]=i;
                    hasNumber[x][y]=true;
                    i++;
                }
                while (y+1<n&&hasNumber[x][y+1]==false){
                    y=y+1;
                    result[x][y]=i;
                    hasNumber[x][y]=true;
                    i++;
                }
                while (x+1<n&&hasNumber[x+1][y]==false){
                    x=x+1;
                    result[x][y]=i;
                    hasNumber[x][y]=true;
                    i++;
                }
                while (y-1>=0&&hasNumber[x][y-1]==false){
                    y=y-1;
                    result[x][y]=i;
                    hasNumber[x][y]=true;
                    i++;
                }
                while (x-1>=0&&hasNumber[x-1][y]==false){
                    x=x-1;
                    result[x][y]=i;
                    hasNumber[x][y]=true;
                    i++;
                }
            }
            for (int j = 0; j <n ; j++) {
                for (int k = 0; k <n ; k++) {
                    System.out.print(result[j][k]+"---");
                }
                System.out.println();
            }
            return  result;
        }
    }

  • 相关阅读:
    欧几里得方程 模幂运算 模乘运算 蒙哥马利模乘 素数测试
    HLG 1058workflow解题报告
    poj 3264Balanced Lineup解题报告
    JavaScript之HTMLCollection接口
    随记2(IE下调试Javascript)
    抽象类和接口
    JavaScript之字符串处理函数
    随记1
    多态
    自动内存管理
  • 原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11481173.html
Copyright © 2011-2022 走看看