【leetcode】Spiral Matrix(middle)
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]
.
思路:就按照螺旋矩阵的规律 用n记录旋转圈数 每圈按左下右上的顺序取值。 注意去重复。
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> ans; if(matrix.empty()) return ans; int M = matrix.size(); int N = matrix[0].size(); for(int n = 0; n < min((M+1)/2,(N+1)/2);n++) { //行 -----> for(int i = n; i < N - n; i++) ans.push_back(matrix[n][i]); //列 向下 for(int i = n + 1; i < M - n; i++) ans.push_back(matrix[i][N - 1 - n]); //行 <----------- if(M - n - 1 <= n) //列号 一定要比向左时的列号小 防止重复 break; for(int i = N - n - 2; i >= n; i--) ans.push_back(matrix[M - n - 1][i]); //列 向上 if(n >= N - 1 - n) //行号 一定要比向下时的行号大 防止重复 break; for(int i = M - n - 2; i >= n + 1; i--) ans.push_back(matrix[i][n]); } return ans; } };
大神思路和我一样,就是用自定义变量来避免重复取行或列。
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (matrix.length == 0) { return res; } int rowBegin = 0; int rowEnd = matrix.length-1; int colBegin = 0; int colEnd = matrix[0].length - 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { // Traverse Right for (int j = colBegin; j <= colEnd; j ++) { res.add(matrix[rowBegin][j]); } rowBegin++; // Traverse Down for (int j = rowBegin; j <= rowEnd; j ++) { res.add(matrix[j][colEnd]); } colEnd--; if (rowBegin <= rowEnd) { // Traverse Left for (int j = colEnd; j >= colBegin; j --) { res.add(matrix[rowEnd][j]); } } rowEnd--; if (colBegin <= colEnd) { // Traver Up for (int j = rowEnd; j >= rowBegin; j --) { res.add(matrix[j][colBegin]); } } colBegin ++; } return res; } }