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;
        }
    }

  • 相关阅读:
    百度地图Api 根据两个坐标点计算距离
    Android 6.0 Permission权限与安全机制
    CentOS安装nginx
    CentOS安装mysq
    CentOS安装JDK
    -bash: /root/java/jdk/bin/java: cannot execute binary file
    数据库连接池之_DButils
    数据库连接池之_c3p0
    数据库连接池之_Druid简单使用
    后台管理平台编辑表格
  • 原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/11481173.html
Copyright © 2011-2022 走看看