Java實(shí)現(xiàn)螺旋矩陣的示例
給定一個(gè)包含 m x n 個(gè)元素的矩陣(m 行, n 列),請(qǐng)按照順時(shí)針螺旋順序,返回矩陣中的所有元素。
示例 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; } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Java8新特性之interface中的static方法和default方法
這篇文章主要介紹了Java8新特性之interface中的static方法和default方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08java request.getHeader("user-agent")獲取瀏覽器信息的方法
這篇文章主要介紹了java request.getHeader("user-agent")獲取瀏覽器信息的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03SpringBoot使用Thymeleaf自定義標(biāo)簽的實(shí)例代碼
這篇文章主要介紹了SpringBoot使用Thymeleaf自定義標(biāo)簽的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2020-09-09Java線程中斷機(jī)制interrupt、isInterrupted、interrupted方法詳解
這篇文章主要介紹了Java線程中斷機(jī)制interrupt、isInterrupted、interrupted方法詳解,一個(gè)線程不應(yīng)該由其他線程來(lái)強(qiáng)制中斷或停止,而是應(yīng)該由線程自己自行停止,所以,Thread.stop、Thread.suspend、Thread. resume都已經(jīng)被廢棄了,需要的朋友可以參考下2024-01-01零基礎(chǔ)寫Java知乎爬蟲之將抓取的內(nèi)容存儲(chǔ)到本地
上一回我們說到了如何把知乎的某些內(nèi)容爬取出來(lái),那么這一回我們就說說怎么把這些內(nèi)容存儲(chǔ)到本地吧。2014-11-11