题目描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Have you met this question in a real interview? Yes ExampleGiven the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]You should return [1,2,3,6,9,8,7,4,5].
题目思路:这题和#381一样,只要设好了boundary,再注意下while loop break的条件,再仔细些就不会有问题。
Mycode(AC = 27ms):
class Solution { public: /** * @param matrix a matrix of m x n elements * @return an integer array */ vector<int> spiralOrder(vector<vector<int>>& matrix) { // Write your code here vector<int> ans; int num_rows = matrix.size(); if (num_rows == 0) return ans; ans.resize(num_rows * matrix[0].size()); int upper_row = 0, down_row = num_rows - 1, left_col = 0, right_col = matrix[0].size() - 1, count = 0; while (count < ans.size()) { // get upper row for (int i = left_col; i <= right_col; i++) { ans[count++] = matrix[upper_row][i]; } upper_row++; if (count >= ans.size()) break; // get right col for (int i = upper_row; i <= down_row; i++) { ans[count++] = matrix[i][right_col]; } right_col--; if (count >= ans.size()) break; // get bottom row for (int i = right_col; i >= left_col; i--) { ans[count++] = matrix[down_row][i]; } down_row--; if (count >= ans.size()) break; // get left col for (int i = down_row; i >= upper_row; i--) { ans[count++] = matrix[i][left_col]; } left_col++; } return ans; } };