螺旋矩阵(暴力算法)
生活随笔
收集整理的這篇文章主要介紹了
螺旋矩阵(暴力算法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
給你一個?m?行?n?列的矩陣?matrix?,請按照?順時針螺旋順序?,返回矩陣中的所有元素。
示例:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 輸出:[1,2,3,6,9,8,7,4,5]解題思路:
? ? ? 當遍歷元素時,當下一個元素超出行數,或者超出列數,或者行數小于0,列數小于0,以及元素被標識了,說明方向要改變了
題解:
public static void main(String[] args) {int[][] matrix = {{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12},{13, 14, 15, 16}};List<Integer> merge = merge(matrix);System.err.println(merge);}public static List<Integer> merge(int[][] matrix) {//存儲結果List<Integer> result = new LinkedList<>();//行的長度int rowLength = matrix.length;//列的長度int colLength = matrix[0].length;//標識元素boolean[][] booleans = new boolean[rowLength][colLength];//用于標識方向,分別是向右,向下,向左,向上int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//計算出總元素的數量int totals = rowLength * colLength;//標識方向的下標,當下標為0就是向右,1就是向下,2向左,3向上int directionIndex = 0;//當前行數int row = 0;//當前列數int col = 0;for (int i = 1; i <= totals; i++) {//將元素加入集合result.add(matrix[row][col]);//標識這個元素已經被遍歷了booleans[row][col] = true;//以原方向,計算下一個行數,和和下一個列數int nextRow = row + direction[directionIndex][0];int nextCol = col + direction[directionIndex][1];//如果超過列數,或者超過行數,或者行數小于0,列數小于0,或者已經被遍歷了,說明要改變方向了,//每四次一個循環,所以用%4,計算方向if (nextRow > rowLength - 1 || nextCol > colLength - 1 || nextCol < 0 || nextRow < 0 || booleans[nextRow][nextCol]) {directionIndex = (directionIndex + 1) % 4;}//改變方向后,計算出行數,和列數row = row + direction[directionIndex][0];col = col + direction[directionIndex][1];}return result;}總結
以上是生活随笔為你收集整理的螺旋矩阵(暴力算法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中的mvc三层结构究竟有什么关系
- 下一篇: RDP 总结(一)