leetcode 之Spiral Matrix I 和 II 解題思路
阿新 • • 發佈:2018-12-30
題目如下:
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]
.
螺旋形狀需要有四個方向,右,下,左,上,再依次進行。當在向右移動時,遇到邊界或者後面一個已經列印過,則改變方向,向下;其它方向依次相同。因此需要有一個二維陣列記錄當前的位置是否列印過,還需要有一個變數記錄已經列印了多少個,當列印的個數和二維陣列總個數相同時,則停止列印。
程式碼如下:
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list = new ArrayList<Integer>(); int nRows = matrix.length; if(nRows == 0) return list; int nCols = matrix[0].length; int total_Len = nRows * nCols;//陣列總長度 int[][] used = new int[nRows][nCols];//用於判斷matrix陣列中的元素是否列印過 int current_DIR = 0;//當前方向 int i = 0; int j = 0; int len = 0; while(true){ if(len == total_Len){//如果當前列印長度和總長度相等,則停止列印 break; } switch(current_DIR){ case 0:{//0代表向右的方向 if(j == nCols || used[i][j] == 1){//改變方向的邊界條件 j--; i++; current_DIR = 1; }else{ list.add(matrix[i][j]); used[i][j] = 1; len++; j++; } break; } case 1:{//1代表向下 if(i == nRows || used[i][j] == 1){ i--; j--; current_DIR = 2; }else{ list.add(matrix[i][j]); used[i][j] = 1; len++; i++; } break; } case 2:{//2代表向左 if(j == -1 || used[i][j] == 1){ j++; i--; current_DIR = 3; }else{ list.add(matrix[i][j]); used[i][j] = 1; len++; j--; } break; } case 3:{//3代表向上 if(i == -1 || used[i][j] == 1){ i++; j++; current_DIR = 0; }else{ list.add(matrix[i][j]); used[i][j] = 1; len++; i--; } } } } return list; } }
Spiral Matrix II
Total Accepted: 10563 Total Submissions: 34583My SubmissionsGiven an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]該題是根據給定的n按照螺旋形狀構造一個n*n的矩陣,方法和列印類似,直接給出程式碼
public class Solution { public int[][] generateMatrix(int n) { if(n == 0) return new int[0][0]; int[][] matrix = new int[n][n]; int len = 0; int total_Len = n * n; int current_Dir = 0; int[][] used = new int[n][n]; int i = 0, j = 0; while(true){ if(len == total_Len){ break; } switch(current_Dir){ case 0:{ if(j == n || used[i][j] == 1){ j--; i++; current_Dir = 1; }else{ matrix[i][j] = ++len; used[i][j] = 1; j++; } break; } case 1:{ if(i == n || used[i][j] == 1){ i--; j--; current_Dir = 2; }else{ matrix[i][j] = ++len; used[i][j] = 1; i++; } break; } case 2:{ if(j == -1 || used[i][j] == 1){ j++; i--; current_Dir = 3; }else{ matrix[i][j] = ++len; used[i][j] = 1; j--; } break; } case 3:{ if(i == -1 || used[i][j] == 1){ i++; j++; current_Dir = 0; }else{ matrix[i][j] = ++len; used[i][j] = 1; i--; } break; } } } return matrix; } }