一、54、螺旋矩阵(中等)
螺旋矩阵是很经典的题目,它不涉及算法,就是简单的模拟,但是细节很多,在面试时一紧张就容易写错。其实可以把整个求解过程拆分成4个部分就不容易搞混。
对于一个矩阵,我们可以规定它的左上角为(top, left) 右上角为(top, right) 左下角为(bottom, left) 右下角为(bottom right),left、top初始值为0,right初始值为列数,bottom初始值为行数,然后按照螺旋矩阵形成的顺序进行模拟:右下左上。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
List<Integer> ans = new LinkedList<>();
if (matrix == null || rows == 0 || columns == 0) return ans;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
// 先遍历top行
for (int column = left; column <= right; column++) {
ans.add(matrix[top][column]);
}
// 再遍历right列
for (int row = top + 1; row <= bottom; row++) {
ans.add(matrix[row][right]);
}
// 当left == right 或者 top == bottom,就成了一条线,不能走
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
ans.add(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
ans.add(matrix[row][left]);
}
}
left++;
top++;
right--;
bottom--;
}
return ans;
}
}
二、螺旋矩阵(蓝桥杯)
和上面方法一样,模拟出矩阵
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
int top = 0, left = 0, right = 29, bottom = 29;
int[][] matrix = new int[35][35];
int cur = 1;
while (left <= right && top <= bottom) {
// 记住遍历顺序:右下左上
for (int col = left; col <= right; col++) {
matrix[top][col] = cur++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = cur++;
}
if (left < right && top < bottom) {
for (int col = right - 1; col > left; col--) {
matrix[bottom][col] = cur++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = cur++;
}
}
left++;
top++;
right--;
bottom--;
}
System.out.println(matrix[19][19]);
}
}
三、螺旋矩阵Ⅱ(中等)
同样也是上一题的方法
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int num = 1;
int top = 0, left = 0, right = n - 1, bottom = n - 1;
while (left <= right && top <= bottom) {
for (int col = left; col <= right; col++) {
ans[top][col] = num++;
}
for (int row = top + 1; row <= bottom; row++) {
ans[row][right] = num++;
}
if (left < right && top < bottom) {
for (int col = right - 1; col >= left; col--) {
ans[bottom][col] = num++;
}
for (int row = bottom - 1; row > top; row--) {
ans[row][left] = num++;
}
}
left++;
top++;
right--;
bottom--;
}
return ans;
}
}