Spiral Matrix II
Problem:
Spiral matrix的马甲。
Solution:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:Given n =
3
,[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]Analysis:
Spiral matrix的马甲。
Solution:
class Solution { public int[][] generateMatrix(int n) { int m = n; int[][] matrix = new int[m][n]; int[] dx = new int[]{0, 1, 0, -1}; int[] dy = new int[]{1, 0, -1, 0}; boolean[][] visited = new boolean[m][n]; int x = 0, y = 0; int d = 0; for (int i = 1; i <= n*n; i++) { matrix[x][y] = i; visited[x][y] = true; int newx = x + dx[d]; int newy = y + dy[d]; if (0 <= newx && newx < m && 0 <= newy && newy < n && !visited[newx][newy]) { x = newx; y = newy; } else { d = (d + 1) % 4; x += dx[d]; y += dy[d]; } } return matrix; } }
评论
发表评论