zoukankan      html  css  js  c++  java
  • 力扣59题(螺旋矩阵)

    59、螺旋矩阵II

    基本思想:

    循环结构

    具体实现:

    全在图里了

    注意左闭右开

    代码:

    class Solution {
        public int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
    
            int loop = n / 2; 
            
            int startX = 0;//初始化每个循环起始位置
            int startY = 0;
            int offset = 1;//控制每一条边遍历的长度
            int count = 1;
            int mid = n / 2;
            while (loop > 0){
                int i = startX;
                int j = startY;
                //上侧的从左到右
                for (; j < startY + n -offset; ++j){///不能包含到这一行的最后一个元素,所以减去偏移量
                    res[startX][j] = count++;
                }
                
                //右侧的从上到下
                for(; i < startX + n - offset; ++i){
                    res[i][j] = count++;
                }
    
                //下侧的从右到左
                for(; j > startY ; --j){
                    res[i][j] = count++;
                }
    
                //左侧的从下到上
                for(; i > startY; --i){
                    res[i][j] = count++;
                }
    
                loop--;
    
                startX += 1;
                startY += 1;
    
                offset += 2;
            }
    
            if (n % 2 == 1){//如果n是一个奇数,最后给中间位置赋值
                res[mid][mid] = count;
            }
    
            return res;
        }
    }
  • 相关阅读:
    pickle模块使用
    Graphviz安装教程
    Redis常用命令
    MongoDB和Redis的区别
    UVA-1572
    poj2352
    poj1195
    Codeforces Round #430 (Div. 2)
    Codeforces Round #431 (Div. 2) B. Tell Your World
    poj3278 【BFS】
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15389748.html
Copyright © 2011-2022 走看看