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]
]
Idea: This problem and spiral matrix problem is similar, there is no difficult place, mainly is the conversion of four directions.
The specific code is as follows:
public class Solution {public int[][] Generatematrix (int n) {int[][] a = new int[n][n]; int o = 0;//defines the direction, 0: Right, 1: Lower, 2: Left, 3: on int x = 0;//1-n2 int i = 0;//row int j = 0;//column while (i >= 0 && i < n && J >= 0 && J < N) {if (A[i][j] > 0) break;//fully filled, end A[I][J] = ++x;//fill data switch (o) {//Direction discussion case 0:if (j = = N-1 | | a[i][j+1] & Gt 0) {i++; o = 1; }else{J + +; } break; Case 1:if (i = = N-1 | | a[i+1][j] > 0) {j--; o = 2; }else{i++; } break; Case 2:if (j = = 0 | | a[i][j-1] > 0) {i--;o = 3; }else{j--; } break; Case 3:if (i = = 0 | | a[i-1][j] > 0) {j + +; o = 0; }else{i--; } break; }} return A; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 59.Spiral Matrix II (Spiral Matrix II) ideas and methods for solving problems