package leetcode.array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Spiral_Matrix_II {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
int x = 0, y = 0;
for (int i = 1, d = 0; i <= n * n; i++) {
res[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a == n || b < 0 || b == n || res[a][b] != 0) {
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
return res;
}
public int[][] generateMatrix3(int n) {
int[][] arr = new int[n][n];
int c = 1, j = 0;
while (c <= n * n) {
for (int i = j; i < n - j; i++)
arr[j][i] = c++;
for (int i = j + 1; i < n - j; i++)
arr[i][n - j - 1] = c++;
for (int i = n - j - 2; i >= j; i--)
arr[n - j - 1][i] = c++;
for (int i = n - j - 2; i > j; i--)
arr[i][j] = c++;
j++;
}
return arr;
}
public List<Integer> spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return new LinkedList<>();
int l = 0;
int r = matrix[0].length - 1;
int u = 0;
int d = matrix.length - 1;
List<Integer> list = new LinkedList<>();
while (l <= r && u <= d){
for (int i = l; i <= r; i++) {
list.add(matrix[u][i]);
}
u++;
for (int i = u; i <= d; i++) {
list.add(matrix[i][r]);
}
r--;
for (int i = r; i >= l && u <= d; i--) {
list.add(matrix[d][i]);
}
d--;
for (int i = d; i >= u && l <= r; i--) {
list.add(matrix[i][l]);
}
l++;
}
return list;
}
}
|