Spiral and Zigzag
阅读原文时间:2023年07月14日阅读:1

【LeetCode】

虽然感觉spiral matrix 两道题和 zigzag conversion 那道题没有太多联系,但是,毕竟都是相当于数学上的找规律题目。

这种优雅的题目就应该用下面这种优雅的代码写法。

054 Spiral Matrix

/* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
*/

class Solution {
public List spiralOrder(int[][] matrix) {
List res = new ArrayList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
int beginX = 0, endX = matrix[0].length - 1;
int beginY = 0, endY = matrix.length - 1;
while(true){
//from left to right
for(int i = beginX; i <= endX; i++) res.add(matrix[beginY][i]); if(++beginY > endY) break;
//from top to bottom
for(int i = beginY; i <= endY; i++) res.add(matrix[i][endX]); if(beginX > --endX) break;
//from right to left
for(int i = endX; i >= beginX; i--) res.add(matrix[endY][i]);
if(beginY > --endY) break;
//from bottom to top
for(int i = endY; i >= beginY; i--) res.add(matrix[i][beginX]);
if(++beginX > endX) break;
}
return res;
}
}

059 Spiral Matrix II

/* Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
] */

class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int beginX = 0, endX = n - 1;
int beginY = 0, endY = n - 1;
int flag = 1;
while(true){
for(int i = beginX; i <= endX; i++) res[beginY][i] = flag++; if(++beginY > endY) break;
for(int i = beginY; i <= endY; i++) res[i][endX] = flag++; if(beginX > --endX) break;
for(int i = endX; i >= beginX; i--) res[endY][i] = flag++;
if(beginY > --endY) break;
for(int i = endY; i >= beginY; i--) res[i][beginX] = flag++;
if(++beginX > endX) break;
}
return res;
}
}

006 Zigzag Conversion

/* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
*/

class Solution {
public:
string convert(string s, int numRows) {
if(numRows <= || s.length() < numRows) return s; string res; for(int i = ;i < numRows;++i) { for(int j = i;j < s.length();j += * (numRows - )) { res += s[j]; if(i > && i < numRows - )
{
if(j + * (numRows - - i) < s.length())
res += s[j + * (numRows - - i)];
}
}
}
return res;
}
};

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器