*Spiral Matrix

mac2022-06-30  87

题目:

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].

 

题解:这道题是实现题。

考虑2个初始条件,如果矩阵只有一行或者一列,那么无需转圈,依次输出即可。

其他情况均需转圈:从左到右,从上到下,从右到左,从下到上。 从大圈依次循环到小圈即可。

 

代码如下:

 

1 public ArrayList<Integer> spiralOrder(int[][] matrix) { 2 ArrayList<Integer> result = new ArrayList<Integer>(); 3 if(matrix == null || matrix.length == 0) 4 return result; 5 6 int m = matrix.length; 7 int n = matrix[0].length; 8 9 int x=0; 10 int y=0; 11 12 while(m>0 && n>0){ 13 14 //if one row/column left, no circle can be formed 15 if(m==1){ 16 for(int i=0; i<n; i++){ 17 result.add(matrix[x][y++]); 18 } 19 break; 20 }else if(n==1){ 21 for(int i=0; i<m; i++){ 22 result.add(matrix[x++][y]); 23 } 24 break; 25 } 26 27 //below, process a circle 28 29 //top - move right 30 for(int i=0;i<n-1;i++) 31 result.add(matrix[x][y++]); 32 33 //right - move down 34 for(int i=0;i<m-1;i++) 35 result.add(matrix[x++][y]); 36 37 //bottom - move left 38 for(int i=0;i<n-1;i++) 39 result.add(matrix[x][y--]); 40 41 //left - move up 42 for(int i=0;i<m-1;i++) 43 result.add(matrix[x--][y]); 44 45 x++; 46 y++; 47 m=m-2; 48 n=n-2; 49 } 50 51 return result; 52 }

reference: http://www.cnblogs.com/springfor/p/3887890.html

 

优化的解法,耗时0ms?!

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; } }

 

转载于:https://www.cnblogs.com/hygeia/p/4630974.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)