首先是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]
.
我的思路是:设定一个moveStep计数,从0,0开始,先向右走m步,然后向下走n-1步,然后向左m-1步,然后向上走n-2步。之后为了再往后走,让m = m - 2,n = n - 2;这样的话相当于开始下一个转圈,直到moveStep到m*n为止~
这里有一个问题,由于m和n很有可能不一样,所以不一样while转一圈才能跳出循环,所以每一个for循环后要判断是否要跳出break。
package testAndfun; import java.util.ArrayList; import java.util.List; public class spriralOrder { List<Integer> list = new ArrayList<Integer>(); public 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; } }
然后是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 ] ]
我的思路与上一题一样,向右n,向下n-1,向左n-1,向上n-2,然后再更新n = n - 2;直到往二维数组里输入了moveStep == 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; } }
时间: 2024-10-17 02:22:42