Spiral Matrix 1&2

Source: Internet
Author: User

1.

Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X 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.

 PackageLeetcode2;ImportJava.util.*; Public classSpiralmatrix { Public StaticArraylist<integer> Spiralorder (int[] matrix) {ArrayList<Integer> res=NewArraylist<integer>(); if(matrix==NULL|| Matrix.length==0){               returnRes; }           intm=matrix.length; intN=matrix[0].length; intX=0; intY=0;  while(N>0 && m>0){             if(m==1){                for(inti=0;i<n;i++) {Res.add (matrix[x][y++]); }                Break; }Else  if(n==1){                  for(inti=0;i<m;i++) {Res.add (matrix[x++][y]); }                   Break; }                           for(inti=0;i<n-1;i++) {Res.add (matrix[x][y++]); }               for(inti=0;i<m-1;i++) {Res.add (matrix[x++][y]); }              for(inti=0;i<n-1;i++) {Res.add (matrix[x][y--]); }               for(inti=0;i<m-1;i++) {Res.add (matrix[x--][y]); } x++; Y++; N=n-2; M=m-2; }           returnRes; }     /** 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 voidMain (string[] args) {//TODO auto-generated Method Stub    }}

Spiral Matrix 1&2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.