zoukankan      html  css  js  c++  java
  • 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].

    只适合方阵的C++实现代码:

    vector<int> spiralOrder(vector<vector<int> > &matrix)
        {
            if(matrix.empty()||matrix[0].empty())
                return vector<int>();
            vector<int> ret;
            int n=matrix.size();
            int count=n*n;
            int i=0;
            int j=0;
            while(count)
            {
                if(count==1)
                {
                    ret.push_back(matrix[i][j]);
                    break;
                }
                for(; j<n-i-1; j++)
                {
                    ret.push_back(matrix[i][j]);
                    count--;
                }
                for(; i<j; i++)
                {
                    ret.push_back(matrix[i][j]);
                    count--;
                }
                for(; j>n-i-1; j--)
                {
                    ret.push_back(matrix[i][j]);
                    count--;
                }
                for(; i>j; i--)
                {
                    ret.push_back(matrix[i][j]);
                    count--;
                }
                i++;
                j++;
            }
            return ret;
        }
  • 相关阅读:
    线性筛素数
    redis集成springmvc
    shiro登录权限认证
    jQuery插件
    maven多项目配置
    w
    触发器
    后悔了可以找我我们是朋友
    url upload data
    排队
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4111548.html
Copyright © 2011-2022 走看看