Java實現(xiàn)螺旋矩陣的示例
給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。
示例 1:
輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例 2:
輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new LinkedList<>();
if(matrix.length==0) return result;
int upBound = 0;
int rightBound = matrix[0].length-1;
int leftBound = 0;
int downBound = matrix.length-1;
while(true){
for(int i=leftBound; i<=rightBound; ++i)
result.add(matrix[upBound][i]);
if(++upBound>downBound) break;
for(int i=upBound; i<=downBound; ++i)
result.add(matrix[i][rightBound]);
if(--rightBound<leftBound) break;
for(int i=rightBound; i>=leftBound; --i)
result.add(matrix[downBound][i]);
if(--downBound<upBound) break;
for(int i=downBound; i>=upBound; --i)
result.add(matrix[i][leftBound]);
if(++leftBound>rightBound) break;
}
return result;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot整合druid及多數(shù)據(jù)源配置的demo
這篇文章主要介紹了springboot整合druid及多數(shù)據(jù)源配置的demo,本篇主要分兩部分 ①springboot整合druid的代碼配置,以及druid的監(jiān)控頁面演示;②對實際場景中多數(shù)據(jù)源的配置使用進行講解,需要的朋友可以參考下2024-01-01
spring security的BCryptPasswordEncoder加密和對密碼驗證的原理分析
文章介紹了加密算法和hash算法的基本概念,以及BCryptPasswordEncoder加密和解密的原理,加密算法是可逆的,需要加鹽以保證安全性,BCryptPasswordEncoder通過生成鹽值并在加密和解密過程中使用,確保相同的明文每次加密結(jié)果不同,從而提高安全性2024-11-11
mybatis中insert返回值為1,但數(shù)據(jù)庫卻沒有數(shù)據(jù)
這篇文章主要介紹了mybatis中insert返回值為1,但數(shù)據(jù)庫卻沒有數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10
Spring Boot Actuator未授權訪問漏洞的問題解決
Spring Boot Actuator 端點的未授權訪問漏洞是一個安全性問題,可能會導致未經(jīng)授權的用戶訪問敏感的應用程序信息,本文就來介紹一下解決方法,感興趣的可以了解一下2023-09-09

