在刷leetcode的時(shí)候又遇到了個(gè)問(wèn)題:
輸入一個(gè)矩陣,按照從外向里以順時(shí)針的順序依次打印出每一個(gè)數(shù)字。
示例 1:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]
示例 2:
輸入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
輸出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100
想了半天,貌似也沒(méi)有什么規(guī)律,話說(shuō)這道題真的是道簡(jiǎn)單的題目么,感覺(jué)有點(diǎn)打臉啊
image.png
image.png
按照我的想法,其實(shí)就是按順序取值八秃,一共有四種操作, 從上到下操作,取 list[0] 的所有順序值即1234,然后 取右值,即取所有剩下數(shù)組的 最后一個(gè)值肉盹。再按順序取下值,最后倒序取左值。
那么結(jié)論來(lái)了,我只需要寫這四種操作,然后迭代調(diào)用就可以完成這個(gè)邊界值問(wèn)題了上忍。
由于OC 比較麻煩,講道理的話還是JS比較簡(jiǎn)潔,還是按照J(rèn)S來(lái)解決這個(gè)問(wèn)題
//定義四個(gè)方向值,
var Direction = {
right : 0, //向右
bottom : 1, //向下
left : 2, //向左
up : 3, //向上
};
var spiralOrder = function(matrix) {
let resultList = [];
var result = iteration(resultList,matrix,Direction.right);
console.log(result);
return result;
};
var iteration = function(resultList,matrix,direction) {
if (!matrix) {
return resultList;
}
// 只有最后一個(gè)時(shí),直接將其拋出
if (matrix.length == 0) {
return resultList;
}
let tempList = [];
switch (direction) {
case(Direction.right) :{
tempList = matrix.shift();
resultList = resultList.concat(tempList);
}
break;
case(Direction.bottom) :{
for (var i = 0; i < matrix.length; i++) {
var lastValue = matrix[i].pop();
// 解決數(shù)組為空的問(wèn)題
if (typeof(lastValue) == "undefined") {
return resultList;
}
resultList.push(lastValue);
}
}
break;
case(Direction.left) :{
tempList = matrix.pop();
resultList = resultList.concat(tempList.reverse());
}
break;
case(Direction.up) :{
for (var i = matrix.length - 1; i >= 0; i--) {
var firstValue = matrix[i][0];
// 解決數(shù)組為空的問(wèn)題
if (typeof(firstValue) == "undefined") {
return resultList;
}
matrix[i].shift();
resultList.push(firstValue);
}
}
break;
}
// 獲取下一個(gè)方向
direction = (direction+1)%4;
return iteration(resultList,matrix,direction);
};
提交代碼,執(zhí)行效果如下:
image.png
題目來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance