[4]54. Spiral Matrix/59. Spiral Matrix II(Java)
2017-09-25 00:19
411 查看
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].
class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix.length == 0) return res; int rowBegin = 0, colBegin = 0; int rowEnd = matrix.length - 1; 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 i = rowBegin; i <= rowEnd; i ++) { res.add(matrix[i][colEnd]); } colEnd --; if (rowBegin <= rowEnd) { // Traverse left for (int j = colEnd; j >= colBegin; j --) { res.add(matrix[rowEnd][j]); } rowEnd --; } if (colBegin <= colEnd) { // Traverse up for (int i = rowEnd; i >= rowBegin; i --) { res.add(matrix[i][colBegin]); } colBegin ++; } } return res; } }
59. Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.For example,
Given n = 3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution { public int[][] generateMatrix(int n) { int[][] matrix = new int ; if (n == 0) return matrix; int rowBegin = 0, colBegin = 0; int rowEnd = n - 1, colEnd = n - 1; int num = 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { // Traverse right for (int j = colBegin; j <= colEnd; j ++) { matrix[rowBegin][j] = num ++; } rowBegin ++; // Traverse down for (int i = rowBegin; i <= rowEnd; i ++) { matrix[i][colEnd] = num ++; } colEnd --; if (rowBegin <= rowEnd) { // Traverse left for (int j = colEnd; j >= colBegin; j --) { matrix[rowEnd][j] = num ++; } rowEnd --; } if (colBegin <= colEnd) { // Traverse up for (int i = rowEnd; i >= rowBegin; i --) { matrix[i][colBegin] = num ++; } colBegin ++; } } return matrix; } }
相关文章推荐
- [leetcode-59]spiral matrixII(java)
- leetcode-java-59. Spiral Matrix II
- (Java)LeetCode-59. Spiral Matrix II
- 59. Spiral Matrix II Leetcode Python
- leetcode 59. Spiral Matrix II
- leetcode59 Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II(待进一步研究)
- 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- LeetCode 59 --- Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- 59. Spiral Matrix II LeetCode
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- leetcode 59. Spiral Matrix II