zoukankan      html  css  js  c++  java
  • 59. Spiral Matrix II(中等,同54题)

    Given an integer (n), generate a square matrix filled with elements from 1 to (n^2) in spiral order.

    For example,
    Given n = 3,
    You should return the following matrix:

    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]
    

    思路完全同 54. Spiral Matrix(中等).
    自个代码:

    vector<vector<int>> generateMatrix(int n) {
    	vector<vector<int>> A(n, vector<int>(n)); //n行n列,动态的
    
    	// Normal Case
    	int rowStart = 0;
    	int rowEnd = n - 1;
    	int colStart = 0;
    	int colEnd = n - 1;
    	int num = 1; //change
    
    	while (rowStart <= rowEnd && colStart <= colEnd) {
    		for (int i = colStart; i <= colEnd; i++) {
    			A[rowStart][i] = num++; //change
    		}
    		rowStart++;
    
    		for (int i = rowStart; i <= rowEnd; i++) {
    			A[i][colEnd] = num++; //change
    		}
    		colEnd--;
    
    		for (int i = colEnd; i >= colStart; i--) {
    			if (rowStart <= rowEnd)
    				A[rowEnd][i] = num++; //change
    		}
    		rowEnd--;
    
    		for (int i = rowEnd; i >= rowStart; i--) {
    			if (colStart <= colEnd)
    				A[i][colStart] = num++; //change
    		}
    		colStart++;
    	}
    	return A;
    }
    
  • 相关阅读:
    ps:图层知识
    ps:选区的存储及载入
    ps:消除锯齿和羽化
    ps:不规则选区
    ps:建立规则选区
    python如何查看内存占用空间
    python-生成器
    python3-列表生成式
    python:迭代
    Photoshop画笔工具的使用
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7439877.html
Copyright © 2011-2022 走看看