[LeetCode]Spiral Matrix

来源:互联网 发布:大数据产品分析 编辑:程序博客网 时间:2024/05/16 06:06

https://leetcode.com/problems/spiral-matrix/

维护上下左右四个边界值,向右遍历一次上++,向下遍历一次右--,向左遍历一次下--,向上遍历一次左++

注意下循环之中的边界判断


public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {                List<Integer> res = new ArrayList<Integer>();                if (matrix.length == 0) {            return res;        }                int rowBegin = 0;        int rowEnd = matrix.length-1;        int colBegin = 0;        int colEnd = matrix[0].length - 1;                while (rowBegin <= rowEnd && colBegin <= colEnd) {            // Traverse Right            for (int j = colBegin; j <= colEnd; j ++) {                res.add(matrix[rowBegin][j]);            }            rowBegin++;                        // Traverse Down            for (int j = rowBegin; j <= rowEnd; j ++) {                res.add(matrix[j][colEnd]);            }            colEnd--;                        if (rowBegin <= rowEnd) {                // Traverse Left                for (int j = colEnd; j >= colBegin; j --) {                    res.add(matrix[rowEnd][j]);                }            }            rowEnd--;                        if (colBegin <= colEnd) {                // Traver Up                for (int j = rowEnd; j >= rowBegin; j --) {                    res.add(matrix[j][colBegin]);                }            }            colBegin ++;        }                return res;    }}



下面是自己的shi做法


public class Solution {    public List<Integer> spiralOrder(int[][] matrix) {        LinkedList<Integer> res = new LinkedList<>();        if (matrix == null || matrix.length == 0) return res;        boolean[][] visit = new boolean[matrix.length][matrix[0].length];        spiralOrder(0, 0, matrix, visit, res, 1);        return res;    }    private void spiralOrder(int x, int y, int[][] matrix, boolean[][] visit, LinkedList<Integer> res, int direct) {        if (x >= matrix.length || x < 0 || y < 0 || y >= matrix[0].length || visit[x][y]) return;        if (direct == 1) {            while (y < matrix[0].length && !visit[x][y]) {                res.add(matrix[x][y]);                visit[x][y++] = true;            }            y--;            x++;        } else if (direct == 2) {            while (x < matrix.length && !visit[x][y]) {                res.add(matrix[x][y]);                visit[x++][y] = true;            }            x--;            y--;        } else if (direct == 3) {            while (y >= 0 && !visit[x][y]) {                res.add(matrix[x][y]);                visit[x][y--] = true;            }            y++;            x--;        } else if (direct == 0) {            while (x >= 0 && !visit[x][y]) {                res.add(matrix[x][y]);                visit[x--][y] = true;            }            x++;            y++;        }        spiralOrder(x, y, matrix, visit, res, (direct + 1) % 4);    }}


0 0
原创粉丝点击