日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Spiral Matrix I II

發布時間:2023/12/20 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.

Example

Given 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.

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].

分析:

拿到左上角和右下角的坐標,然后從上,右,下,左打印。然后更新坐標。

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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。