Middle-题目111:54. 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].
题目大意:
按顺时针螺旋顺序遍历二维数组。
题目分析:
Middle-题目29很像,在前面题基础上简单改一下代码即可。一个是读数组一个是写数组,所以读数组要使用一个visited[][]数组维护是否读过,而写数组只要判断是否为0即可。
源码:(language:java)

public class Solution {
    private  final int RIGHT = 1;
    private  final int DOWN = 2;
    private  final int LEFT = 3;
    private  final int UP = 4;
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<Integer>();
        int row = matrix.length;
        if(row==0)
            return list;
        int col = matrix[0].length;
        boolean[][] visited = new boolean[row][col];
        int count = 0,direction = RIGHT,i=0,j=0;
        while (count < row * col) {
            list.add(matrix[i][j]);
            visited[i][j] = true;
            switch (direction) {
                case RIGHT:
                    if (j==col-1 || visited[i][j+1]) {
                        direction=DOWN;
                        i++;
                    }
                    else 
                        j++;
                    break;
                case DOWN:
                    if (i==row-1 || visited[i+1][j]) {
                        direction = LEFT;
                        j--;
                    }
                    else
                        i++;
                    break;
                case LEFT:
                    if (j==0 || visited[i][j-1]) {
                        direction = UP;
                        i--;
                    }
                    else
                        j--;
                    break;
                case UP:
                    if (visited[i-1][j]) {
                        direction = RIGHT;
                        j++;
                    }
                    else
                        i--;
                    break;
                default:
                    break;
            }
            count++;
        }
        return list;
    }
}

成绩:
1ms,beats 3.18%,众数1ms,71.07%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值