The first is 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]
.
My idea is: set a movestep count, starting from 0, 0, first go to the right m step, then go down n-1 step, then left m-1 step, and then walk up n-2 step. Then, in order to walk backwards, let m = M-2,n = N-2, so that it is equivalent to start the next circle, until Movestep to M*n ~
There is a problem here, because M and n are very likely different, so not the same while a circle to jump out of the loop, so after each for loop to determine whether to jump out of the break.
Package Testandfun;import Java.util.arraylist;import Java.util.list;public class Spriralorder {List<Integer> List = new arraylist<integer> ();p ublic static void Main (string[] args) {Spriralorder so = new Spriralorder (); int[][] m = {{1,2,3},{4,5,6},{7,8,9}};//int[][] m = {{2,3}}; System.out.println (So.spiralorders (M). ToString ());} Public list<integer> spiralorders (int[][] matrix) {if (matrix.length==0 | | matrix[0].length==0) return List; int movestep = 0; int m = matrix[0].length; int n = matrix.length; int x=0,y=-1; while (Movestep!=matrix.length*matrix[0].length) {for (int i=0;i<m;i++) {list.add (matrix[x][++y]); movestep++; } if (movestep==matrix.length*matrix[0].length) break; for (int i=0;i<n-1;i++) {list.add (matrix[++x][y]); movestep++; } if (movestep==matrix.length*matrix[0].length) break; for (int i=0;i<m-1;i++) {list.add (matrix[x][--y]); Movestep++; } if (movestep==matrix.length*matrix[0].length) break; for (int i=0;i<n-2;i++) {list.add (matrix[--x][y]); movestep++; } n = n-2; m = m-2; } return list; }}
Then the 2:
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]]
My idea is the same as the previous question, right n, down n-1, left n-1, up n-2, and then update n = n-2; until you enter movestep = = In the two-dimensional array n*n
Package Testandfun;import Java.util.arrays;public class Spiralmatrix {public static void main (string[] args) { Spiralmatrix sm = new Spiralmatrix (); System.out.println (Arrays.deeptostring (Sm.generatematrix (3));} Public int[][] Generatematrix (int n) {int[][] out = new Int[n][n]; if (n<=0) return out; int x=0; int y=-1; int movestep = 0; while (movestep! = n*n) {for (int i=0;i<n;i++) { out[x][++y] = ++movestep; } for (int i=0;i<n-1;i++) { out[++x][y] = ++movestep; } for (int i=0;i<n-1;i++) { out[x][--y] = ++movestep; } for (int i=0;i<n-2;i++) { out[--x][y] = ++movestep; } n = n-2; } return out;}}
"Leetcode" Spiral Matrix One and two in JAVA