Spiral Matrix II
leetcode: https://leetcode.com/problems/spiral-matrix-ii/
Description:
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
Idea:
solution1:
Step1: set two index for the round(one for row and the other for column), and index of the number of times to loop
Step2: the number of the rounds we need take is n/2. if the number is odd, we need to assign the value to the array central, if the number if even, when all rounds finished, all the elements will be assigned.
Step3: set two index of loop and set the same interval rule of the loop for each side of the square, for example, in each side only include from the first element to penultimate element, and left the last element for next side(as the first element)
Code:
class Solution {
public int[][] generateMatrix(int n) {
//initialize the result array
int[][] result = new int[n][n];
//set the bound index for round
int bound_i = 0, bound_j =0;
//set the index to reocrd the number of times it has looped
int loop = 0;
//to give each element value with self-increase it
int count = 1;
// set two index for the loop
int i,j;
//n/2 means the number of times it needed
while(loop < n/2){
//make two loop index point to the correct bound of the current round
i=bound_i;
j=bound_j;
//upper side, and just move the column index to assign the value to all element in this row
//each side don't deal with the last element and left them as the first element for the next side
for(j=bound_j; j<n-1-loop; j++){
result[i][j] = count++;
}
//right side, just move row index, and because the last loop has move the column index to the right index.
for(i=bound_i; i<n-1-loop; i++){
result[i][j] = count++;
}
//bottom side, move it back to the start bound of this round
for(;j>bound_j; j--){
result[i][j] = count++;
}
//left side
for(;i>bound_i; i--){
result[i][j] = count++;
}
//narrowing the bound to next round
bound_i++;
bound_j++;
loop++;
}
if (n%2 == 1){
result[n/2][n/2] = count++;
}
return result;
}
}