关闭

Middle-题目111:54. Spiral Matrix

101人阅读 评论(0) 收藏 举报
分类:

题目原文:
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%

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:56956次
    • 积分:3213
    • 等级:
    • 排名:第10664名
    • 原创:270篇
    • 转载:53篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论