54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example, Given the following matrix:

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

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

题目要求按照螺旋线的顺序对一个矩阵 进行遍历,目的和方法很明确,就是先在一行上从左向右遍历,再从行的末端从上到下遍历…………不再赘述。

问题的关键在于确定好循环的边界,那么我们引入up down left right作为每次遍历的边界,初始时分别指向第一行,最后一行,第一列,最后一列。那么在循环过程中,这四个值的变化情况为:

  1. 对最上一行遍历之后,up++
  2. 对最右边一列遍历之后,right–
  3. 对最下一行遍历之后,down–
  4. 对最左列进行遍历后,left++

代码具体如下:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.empty()) 
            return {};
        int row=matrix.size(),col=matrix[0].size();
        int up=0,down=row-1,left=0,right=col-1,k=0,i=0;
        vector<int> res(row*col);
        while(1){
            for(i=left;i<=right;i++)
                res[k++]=matrix[up][i];
            if(++up>down)
                break;
            
            for(i=up;i<=down;i++)
                res[k++]=matrix[i][right];
            if(--right<left)
                break;
            
            for(i=right;i>=left;i--)
                res[k++]=matrix[down][i];
            if(--down<up)
                break;
                
            for(i=down;i>=up;i--)
                res[k++]=matrix[i][left];
            if(++left>right)
                break;
        }
        return res;
    }
};

59. 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 ]
]

这道题的思路和Spiral Matrix I如出一辙,只不过变成了给出大小,要求生成一个螺旋矩阵,我们依然声明up down left right四个变量,思路没什么差别,所以不再赘述。

代码如下:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        if(!n)
            return {};
        vector<vector<int>> res(n,vector<int>(n, 0));/*初始化的时候要仔细考虑,第一次submission因为初始化导致了RTE*/
        int up=0,down=n-1,left=0,right=n-1,i=0,j=0,k=0,num=1;
        while(true){
            for(k=left;k<=right;k++){
                res[up][k]=num;
                num+=1;
            }
            if(++up>down)
                break;
            for(k=up;k<=down;k++){
                res[k][right]=num;
                num+=1;
            }
            if(--right<left)
                break;
            for(k=right;k>=left;k--){
                res[down][k]=num;
                num+=1;
            }
            if(--down<up)
                break;
            for(k=down;k>=up;k--){
                res[k][left]=num;
                num+=1;
            }
            if(++left>right)
                break;
        }
        return res;
    }
};

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017