zoukankan      html  css  js  c++  java
  • lintcode-185-矩阵的之字型遍历

    185-矩阵的之字型遍历

    给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历。

    样例

    对于如下矩阵:
    [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10, 11, 12]
    ]
    返回 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]

    标签

    LintCode 版权所有 矩阵

    思路

    参考http://blog.csdn.net/wutingyehe/article/details/46629087

    code

    class Solution {
    public:
        /**
         * @param matrix: a matrix of integers
         * @return: a vector of integers
         */
        vector<int> printZMatrix(vector<vector<int> > &matrix) {
            // write your code here
            int sizeRow = matrix.size();
            if (sizeRow <= 0) {
                return vector<int>();
            }
            int sizeCol = matrix[0].size();
            if (sizeCol <= 0) {
                return vector<int>();
            }
    
            vector<int> result;
            int count = sizeRow * sizeCol, curRow = 0, curCol = 0;
            result.push_back(matrix[0][0]);
            for (int i = 1; i < count; ) {
                //斜上走到顶
                while (i < count && curRow - 1 >= 0 && curCol + 1 < sizeCol) {
                    result.push_back(matrix[--curRow][++curCol]);
                    i++;
                }
                //横右走一步,不可横右走时竖下走一步
                if (i < count && curCol + 1 < sizeCol) {
                    result.push_back(matrix[curRow][++curCol]);
                    i++;
                }
                else if (i < count && curRow + 1 < sizeRow) {
                    result.push_back(matrix[++curRow][curCol]);
                    i++;
                }
                //斜下走到底
                while (i < count && curRow + 1 < sizeRow && curCol - 1 >= 0) {
                    result.push_back(matrix[++curRow][--curCol]);
                    i++;
                }
                //竖下走一步,不可竖下走时横右走一步
                if (i < count && curRow + 1 < sizeRow) {
                    result.push_back(matrix[++curRow][curCol]);
                    i++;
                }
                else if (i < count && curCol + 1 < sizeCol) {
                    result.push_back(matrix[curRow][++curCol]);
                    i++;
                }
            }
            return result;
        }
    };
    
  • 相关阅读:
    推箱子(简易版)
    [LeetCode] Word Ladder II
    [LeetCode] Path Sum
    [LeetCode] Word Ladder
    DFS & BFS
    [LeetCode] Surrounded Regions
    [LeetCode] Add Binary
    [LeetCode] Plus One
    [LeetCode] Single Number II
    [LeetCode] Single Number
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7289476.html
Copyright © 2011-2022 走看看