题目描述:
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:1 2 3 45 6 7 89 10 11 1213 14 15 16则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
leetcode的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].
解析:对于m*n的矩阵,螺旋读取用了两种,其实差别不大,第一种:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix == null)
return res;
int m = matrix.length;
int n = matrix[0].length;
int left = 0;
int right = n - 1;
int top = 0;
int bottom = m - 1;
while(left < right && top < bottom){
for(int i = left;i < right;i++){
res.add(matrix[top][i]);
}
for(int j = top;j < bottom;j++){
res.add(matrix[j][right]);
}
for(int i = right;i > left;i--){
res.add(matrix[bottom][i]);
}
for(int j = bottom;j > top;j--){
res.add(matrix[j][left]);
}
right--;
left++;
top++;
bottom--;
}
if(left == right){
for(int i = top;i <= bottom;i++)
res.add(matrix[i][left]);
}else if(top == bottom){
for(int i = left;i <= right;i++)
res.add(matrix[top][i]);
}
return res;
}
}
第二种:
import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(matrix==null||matrix.length==0||matrix[0].length==0)
return result;
int m = matrix.length;
int n = matrix[0].length;
int left=0;
int right=n-1;
int top = 0;
int bottom = m-1;
while(result.size()<m*n){
for(int j=left; j<=right; j++){
result.add(matrix[top][j]);
}
top++;
if(bottom<top)
break;
for(int i=top; i<=bottom; i++){
result.add(matrix[i][right]);
}
right--;
if(right<left)
break;
for(int j=right; j>=left; j--){
result.add(matrix[bottom][j]);
}
bottom--;
for(int i=bottom; i>=top; i--){
result.add(matrix[i][left]);
}
left++;
}
return result;
}
}
我以为第二种会比第一种稍微快点,但是在牛客上提交运行的结果是第一种32ms,第二种34ms,不理解。
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,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int k = 1;
int top = 0, bottom = n - 1, left = 0, right = n - 1;
while (left < right && top < bottom) {
for (int j = left; j < right; j++) {
res[top][j] = k++;
}
for (int i = top; i < bottom; i++) {
res[i][right] = k++;
}
for (int j = right; j > left; j--) {
res[bottom][j] = k++;
}
for (int i = bottom; i > top; i--) {
res[i][left] = k++;
}
left++;
right--;
top++;
bottom--;
}
if(n % 2 == 1)
res[n/2][n/2] = k;
return res;
}
}