zoukankan      html  css  js  c++  java
  • Spiral Matrix II

    题目:Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example,Given n = 3,

    You should return the following matrix:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    思路:

    与上一题一样的思路,上次是取数,这次是赋值。

    定义一个count变量即可。

    四条线路法,定义up,right,down,left四个变量,先走最上面,再走最右边,再走最下面,再走最左边,条件结束标志为左等于右,上等于下。

    代码:

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int> > matrix(n,vector<int>(n,0));
            //vector<vector<bool> >dp(m+1,vector<bool>(n+1,false));
            //int matrix[n][n];
            vector<vector<int>> result;
            if(n==0){
                return result;
            }
            
            int left=0,right=n-1;
            int up=0,down=n-1;
            int count=0;
            
            while(up<=down&&left<=right){
                for(int i=left;i<=right;i++){
                    matrix[up][i]=++count;
                    //res.push_back(matrix[up][i]);
                    //matrix[up].push_back(++count);
                }
                
                for(int i=up+1;i<=down;i++){
                    matrix[i][right]=++count;
                    //res.push_back(matrix[i][right]);
                }
                
                if(up==down||left==right){    
                    break;
                }
                
                for(int i=right-1;i>=left;i--){
                    matrix[down][i]=++count;
                    //res.push_back(matrix[down][i]);
                }
                
                for(int i=down-1;i>=up+1;i--){
                    matrix[i][left]=++count;
                    //res.push_back(matrix[i][left]);
                }
                up++;
                right--;
                down--;
                left++;
            }
            
            return matrix;
            
        }
    };


  • 相关阅读:
    P1182 数列分段`Section II` 二分
    洛谷 P1025 数的划分
    深浅拷贝
    数据的内置方法
    控制流程-if/while/for
    python的基本运算符
    花式赋值
    python的注释
    Python的垃圾回收机制
    变量与常量
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519871.html
Copyright © 2011-2022 走看看