T54. Spiral Matrix【Medium】
題目
給一個(gè) m × n 的矩陣(m 行,n 列),按螺旋順序返回所有元素。
例如,
給出如下矩陣:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
你應(yīng)該返回: [1,2,3,6,9,8,7,4,5]
思路
看到這道題我的反應(yīng)是遞歸什么的,然而當(dāng)我看到 Top Solution 的時(shí)候,仿佛打開了新世界的大門,雖然說代碼很長,但是,差不多一看就知道代碼的意思,因?yàn)樗褪峭昝榔鹾狭宋覀儾挥么a解決這個(gè)問題的思路。
就是,哈哈: 拿只筆畫圈圈!

你沒有看錯(cuò),你只要像我這樣畫一個(gè)這么難看的圖片,這就是本題的思路了!
畫圈圈時(shí)有兩個(gè)點(diǎn):
① 畫完一行(列),下次再到這行(列)時(shí)會(huì)畫它的內(nèi)圈
② 當(dāng)畫到最后,兩線不能相交(就是下面的 boundriesCrossed 的作用)
代碼
代碼取自 Top Solution,稍作注釋
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> spiralList = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) return spiralList;
// 設(shè)置初始值
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(true){
// 畫上面的那行
for(int j=left; j <=right;j++){
spiralList.add(matrix[top][j]);
}
//下一次內(nèi)行
top++;
//每畫一行(列) 判斷下一行(列)有沒有越界,有的話跳出循環(huán)
if(boundriesCrossed(left,right,bottom,top))
break;
// 畫最右邊的列
for(int i=top; i <= bottom; i++){
spiralList.add(matrix[i][right]);
}
//下一次內(nèi)列
right--;
if(boundriesCrossed(left,right,bottom,top))
break;
//畫下面的那行
for(int j=right; j >=left; j--){
spiralList.add(matrix[bottom][j]);
}
//下一次內(nèi)行
bottom--;
if(boundriesCrossed(left,right,bottom,top))
break;
//畫左邊的列
for(int i=bottom; i >= top; i--){
spiralList.add(matrix[i][left]);
}
//下一次內(nèi)列
left++;
if(boundriesCrossed(left,right,bottom,top))
break;
}
return spiralList;
}
//每畫一行(列) 判斷下一行(列)有沒有越界,有的話跳出循環(huán)
public boolean boundriesCrossed(int left,int right,int bottom,int top){
if(left>right || bottom<top)
return true;
else
return false;
}