#185 Matrix Zigzag Traversal

题目描述:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order.

Example

Given a matrix:

[
  [1, 2,  3,  4],
  [5, 6,  7,  8],
  [9,10, 11, 12]
]

return [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]

题目思路:

这题也没啥算法可言,就是要好好算好这个index应该放matrix的哪个数,然后一个一个放进去即可。

Mycode(AC = 13ms):

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
        vector<int> ans;
        int num_row = matrix.size();
        if (num_row == 0) return ans;
        int num_col = matrix[0].size();
        
        ans.resize(num_row * num_col);
        printZMatrix(matrix, ans, 0, 0);
        return ans;
    }
    
    void printZMatrix(vector<vector<int> > &matrix,
                      vector<int>& ans,
                      int col_idx,
                      int idx)
    {
        if (idx >= ans.size()) {
            return;
        }
        
        int index = idx;
        
        // upper line
        for (int i = col_idx; i < 2 + col_idx; i++) {
            if (i >= 0 && i < matrix[0].size()) {
                ans[index++] = matrix[0][i];
            }
        }
        
        // '/' line
        int row = 1, col = col_idx;
        while (row < matrix.size()) {
            if (col >= 0 && col < matrix[0].size()) {
                ans[index++] = matrix[row][col];
            }
            row++; col--;
        }
        
        // bottom line and another '/' line
        row--; col += 2;
        while (row > 0) {
            if (col >= 0 && col < matrix[0].size()) {
                ans[index++] = matrix[row][col];
            }
            row--; col++;
        }
        
        printZMatrix(matrix, ans, col_idx + 2, index);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值