1.
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.Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
package leetcode2; import java.util.*; public class SpiralMatrix { public static ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> res=new ArrayList<Integer>(); if(matrix==null||matrix.length==0){ return res; } int m=matrix.length; int n=matrix[0].length; int x=0; int y=0; while(n>0 && m>0){ if(m==1){ for(int i=0;i<n;i++){ res.add(matrix[x][y++]); } break; }else if(n==1){ for(int i=0;i<m;i++){ res.add(matrix[x++][y]); } break; } for(int i=0;i<n-1;i++){ res.add(matrix[x][y++]); } for(int i=0;i<m-1;i++){ res.add(matrix[x++][y]); } for(int i=0;i<n-1;i++){ res.add(matrix[x][y--]); } for(int i=0;i<m-1;i++){ res.add(matrix[x--][y]); } x++; y++; n=n-2; m=m-2; } return res; } /* * SpiralMatrix2 * public int[][] generateMatrix(int n) { int[][] res=new int[n][n]; int top=0; int left=0; int botton=n-1; int right=n-1; int k=1; while(top<botton&&left<right){ for(int i=left;i<right;i++){ res[top][i]=k++; } for(int i=top;i<botton;i++){ res[i][right]=k++; } for(int i=right;i>left;i--){ res[botton][i]=k++; } for(int i=botton;i>top;i--){ res[i][left]=k++; } left++; right--; top++; botton--; } if(n%2!=0){ res[n/2][n/2]=k; } return res; } */ public static void main(String[] args) { // TODO Auto-generated method stub } }
时间: 2024-10-13 01:34:32