Spiral Matrix I II
生活随笔
收集整理的這篇文章主要介紹了
Spiral Matrix I II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spiral Matrix I
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
ExampleGiven n =?3,
You should return the following matrix:
[[ 1, 2, 3 ],[ 8, 9, 4 ],[ 7, 6, 5 ] ]分析:
從上,右,下,左打印。
1 public class Solution { 2 /** 3 * @param n an integer 4 * @return a square matrix 5 */ 6 public int[][] generateMatrix(int n) { 7 8 int[][] arr = new int[n][n]; 9 int a = 0; 10 int b = n - 1; 11 int k = 1; 12 13 while (a < b) { 14 for (int i = a; i <= b; i++) { 15 arr[a][i] = k++; 16 } 17 18 for (int i = a + 1 ; i <= b - 1; i++) { 19 arr[i][b] = k++; 20 } 21 22 for (int i = b ; i >= a; i--) { 23 arr[b][i] = k++; 24 } 25 26 for (int i = b - 1 ; i >= a + 1; i--) { 27 arr[i][a] = k++; 28 } 29 30 a++; 31 b--; 32 } 33 34 if (a == b) { 35 arr[a][b] = k; 36 } 37 return arr; 38 } 39 }
?
Spiral Matrix II
Given a matrix of?m?x?n?elements (m?rows,?n?columns), return all elements of the matrix in spiral order.
ExampleGiven the following matrix:
[[ 1, 2, 3 ],[ 4, 5, 6 ],[ 7, 8, 9 ] ]You should return?[1,2,3,6,9,8,7,4,5].
分析:
拿到左上角和右下角的坐標,然后從上,右,下,左打印。然后更新坐標。
1 public class Solution { 2 public List<Integer> spiralOrder(int[][] matrix) { 3 List<Integer> list = new ArrayList<>(); 4 5 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return list; 6 int a = 0, b = 0; 7 int x = matrix.length - 1, y = matrix[0].length - 1; 8 9 while (a <= x && b <= y) { 10 // top row 11 for (int i = b; i <= y; i++) { 12 list.add(matrix[a][i]); 13 } 14 // right column 15 for (int i = a + 1; i <= x - 1; i++) { 16 list.add(matrix[i][y]); 17 } 18 // bottom row 19 if (a != x) { 20 for (int i = y; i >= b; i--) { 21 list.add(matrix[x][i]); 22 } 23 } 24 // left column 25 if (b != y) { 26 for (int i = x - 1; i >= a + 1; i--) { 27 list.add(matrix[i][b]); 28 } 29 } 30 31 a++; 32 b++; 33 x--; 34 y--; 35 } 36 return list; 37 } 38 }?
轉載于:https://www.cnblogs.com/beiyeqingteng/p/5680666.html
總結
以上是生活随笔為你收集整理的Spiral Matrix I II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机app性能测试简介了解
- 下一篇: c语言24小时计时法转换为12小时,12