Lintcode: Matrix Zigzag Traversal
2016-02-01 05:24
375 查看
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order. Have you met this question in a real interview? Yes 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] Tags Expand
先斜上走到顶,再斜下走到底,直到计数器满, 写的时候老是fail,才发现14行for循环i不需要++,循环里面自己加了
注意corner cases, 以斜上为例
如果是
1,2
5,6
9,10
中6的这种情况,下一个点是10,则x = x+2, y=y-1
如果是1这种情况, 下一个点是2,则只需x = x+1
public class Solution { /** * @param matrix: a matrix of integers * @return: an array of integers */ public int[] printZMatrix(int[][] matrix) { // write your code here if (matrix==null || matrix.length==0 || matrix[0].length==0) return null; int m = matrix.length; int n = matrix[0].length; int count = m*n; int[] res = new int[count]; int x=0, y=0; for (int i=0; i<count;) { while (x>=0 && y<n) { res[i++] = matrix[x--][y++]; } if (i == count) break; if (x<0 && y<n) { x++; } else { x = x+2; y = y-1; } while (x<m && y>=0) { res[i++] = matrix[x++][y--]; } if (i == count) break; if (x<m && y<0) { y++; } else { x = x-1; y = y+2; } } return res; } }
相关文章推荐
- 什么是image crop?
- ios9 第三方SDK无法回调问题
- ubuntu下git安装使用
- 关于python 自带csv库的使用心得 附带操作实例以及excel下乱码的解决
- Python Decorators 装饰器
- 蓝桥杯 算法训练 2的次幂表示(构造)
- windows server上配置 apache + php + MySQL + wordpress
- windows命令行长度的限制
- 【Leetcode】Subsets
- 【Leetcode】Maximum Size Subarray Sum Equals k
- [Regex Expression] Use Shorthand to Find Common Sets of Characters
- [Regex Expression] Find Sets of Characters
- STLport在vc6中的集成
- SDK Hello world(直接使用SDK封装)
- [Regular Expressions] Find Repeated Patterns
- 一个类有多个基类的内存布局
- openCV学习记录:滤镜:重影&暗调
- 写个测试程序看看磁盘映像文件中哪个扇区可以使用?
- 在服务中以当前用户身份启动一个程序
- curl详解