• Spiral Matrix(LintCode)


    Spiral Matrix

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

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

    难得的一次AC! 虽然感觉题很水,但是像这样思路清晰的写下来,没有出任何的“小问题”,然后提交,AC的情况对我来说还是很少的。虽然代码依旧有些乱。

    想法就是定义一个方向的二维数组,从(0,0)开始沿一个方向遍历,若碰壁(下个遍历目标越界或已被遍历)就一个不会碰壁的方向继续遍历;每一个方向都碰壁时结束。

     1 public class Solution {
     2     /**
     3      * @param matrix a matrix of m x n elements
     4      * @return an integer list
     5      */
     6      int[][] f = new int[1000][1000];
     7     public List<Integer> spiralOrder(int[][] matrix) {
     8         List<Integer> list = new ArrayList<Integer>();
     9         int m = matrix.length;
    10         if(m == 0) return list;
    11         int n = matrix[0].length;
    12         
    13         int[][] d = new int[4][2];
    14         d[0][0] = 0; d[0][1] = 1;
    15         d[1][0] = 1; d[1][1] = 0;
    16         d[2][0] = 0; d[2][1] = -1;
    17         d[3][0] = -1; d[3][1] = 0;
    18         
    19         int cd = 0;
    20         int i = 0;
    21         int j = 0;
    22         list.add(matrix[0][0]);
    23         f[0][0] = 1;
    24         boolean flag = true;
    25         while(flag) {
    26             if(!isV(i,j,d[cd],m,n)){
    27                 int x = 0;
    28                 while(!isV(i,j,d[cd],m,n) && x < 4) {
    29                     cd = (cd + 1) % 4;
    30                     x++;
    31                 }
    32                 if(x >= 4) flag = false;
    33             }else {
    34                 i += d[cd][0];
    35                 j += d[cd][1];
    36                 list.add(matrix[i][j]);
    37                 f[i][j] = 1;
    38             }
    39         }
    40         
    41         return list;
    42     }
    43     
    44     boolean isV(int i ,int j ,int d[] ,int m ,int n) {
    45         if(i + d[0] < 0 || i + d[0] >= m) return false;
    46         if(j + d[1] < 0 || j + d[1] >= n) return false;
    47         if(f[i + d[0]][j + d[1]] != 0)return false;
    48         return true;
    49     }
    50 }
    View Code
  • 相关阅读:
    html+css学习
    mac安装软件系列
    Versions 出现 SVN Working Copy xxx locked
    linux安装gcc-c++
    linux常用命令
    linux挂载磁盘
    对jquery新增加的class绑定事件
    linux下安装php的mcrypt拓展
    Linux关闭selinux
    linux安装包资源库
  • 原文地址:https://www.cnblogs.com/FJH1994/p/5031328.html
Copyright © 2020-2023  润新知