[Leetcode 54, Medium] Spiral Matrix

来源:互联网 发布:ubuntu 网络调试工具 编辑:程序博客网 时间:2024/05/19 03:42

Problem:

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

Analysis:


Solutions:

C++:

    vector<int> spiralOrder(vector<vector<int> > &matrix) {        vector<int> result;        if(matrix.empty() || matrix[0].empty())            return result;                    int row_bound = matrix.size();        int col_bound = matrix[0].size();        int search_bound = min(matrix.size(), matrix[0].size()) / 2;        for(int i = 0; i < search_bound; ++i) {            for(int j = i; j < col_bound - i - 1; ++j)                result.push_back(matrix[i][j]);                            for(int j = i; j < row_bound - i - 1; ++j)                result.push_back(matrix[j][col_bound - i - 1]);                            for(int j = col_bound - i - 1; j > i; --j)                result.push_back(matrix[row_bound - i - 1][j]);                            for(int j = row_bound - i - 1; j > i; --j)                result.push_back(matrix[j][i]);        }                if(min(matrix.size(), matrix[0].size()) % 2 != 0) {            for(int i = search_bound; i < max(row_bound, col_bound) - search_bound; ++i) {                if(row_bound > col_bound) {                    result.push_back(matrix[i][search_bound]);                } else if(row_bound <= col_bound) {                    result.push_back(matrix[search_bound][i]);                }            }        }                return result;    }
Java:


Python:

0 0
原创粉丝点击