第一题:横向正序的m*n矩阵,用螺旋形式打印出来
private static List<Integer> spiralOrder(int[][] matrix) {
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
int m = matrix.length, n = matrix[0].length;
List<Integer> ans = new ArrayList();
int num = 1, tar = m * n;
while (num <= tar) {
for (int i = left; i <= right; i++) {
ans.add(matrix[top][i]);
num++;
}
if (num > tar) {
break;
}
top++;// 最上面一行赋值后,top行就变成了第二行
for (int i = top; i <= bottom; i++) {
ans.add(matrix[i][right]);
num++;
}
if (num > tar) {
break;
}
right--;// 同理,最右列左移一位
for (int i = right; i >= left; i--) {
ans.add(matrix[bottom][i]);
num++;
}
if (num > tar) {
break;
}
bottom--;
for (int i = bottom; i >= top; i--) {
ans.add(matrix[i][left]);
num++;
}
if (num > tar) {
break;
}
left++;
}
return ans;
}
第二题:
题目如下:力扣,给定的n阶乱序矩阵,但螺旋打印正序。将其横向打印出来
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
package Array;
import java.util.Arrays;
/**
* Demo class
*
* @author
* @date 2022/7/15
*/
public class Matrix {
public static int[][] buildMatrix(int n) {
int left = 0, right = n - 1, top = 0, bottom = n - 1;
int[][] mat = new int[n][n];
int num = 1, tar = n * n;
while (num <= tar) {
for (int i = left; i <= right; i++) {
mat[top][i] = num++; // left to right.
}
top++;// 最上面一行赋值后,top行就变成了第二行
for (int i = top; i <= bottom; i++) mat[i][right] = num++; // top to bottom.
right--;// 同理,最右列左移一位
for (int i = right; i >= left; i--) mat[bottom][i] = num++; // right to left.
bottom--; // 同理,最下行上移一位
for (int i = bottom; i >= top; i--) mat[i][left] = num++; // bottom to top.
left++; // 同理,最左列左移一列
}
return mat;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(buildMatrix(3)));
}
}