[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
- [leetcode]Spiral Matrix&&Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- LeetCode | Spiral Matrix /Spiral Matrix II
- 【Leetcode】【python】Spiral Matrix/Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix
- [Leetcode] Spiral Matrix II
- LeetCode: Spiral Matrix
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode] Spiral Matrix
- leetcode 80: Spiral Matrix
- [Leetcode] Spiral Matrix
- [LeetCode]Spiral Matrix
- [LeetCode]Spiral Matrix II
- SQL中left join ,right join ,innerjoin 区别
- MyBatis快速入门
- Recycleview内容靠左
- Google Developers中国网站发布!
- i++与++i的区别
- [LeetCode]Spiral Matrix
- 得到当前电脑日期的前后两天
- SQLserver学习day04 T-SQL数据操作(增,删,改) 数据的导入导出 批处理
- 关于教育
- 原理
- 1051. 复数乘法 (15)
- [Lintcode]Maximum Subarray II 最大子数组 II
- 排序算法
- 图的邻接表存储