Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] Solution 1:
class Solution {
public int[][] generateMatrix(int num) {
int[][] spiralMatrix = new int[num][num];
int m = num;
int n = num;
int i =0;
int j = 0;
int k;
int number = 1;
while(j<n && i<m){
for( k=j;k<n;k++){
spiralMatrix[i][k] = number;
number++;
//System.out.println(spiralMatrix[i][k]+" "+i+" "+k);
}
i++;
for( k = i;k<m;k++){
spiralMatrix[k][n-1] = number;
number++;
// System.out.println(spiralMatrix[k][n-1]+" "+k+" "+(n-1));
}
n--;
if(i<m){
for( k = n-1; k>=j;--k){
spiralMatrix[m-1][k] = number;
number++;
// System.out.println(spiralMatrix[m-1][k]+" "+(m-1)+" "+k);
}
m--;
}
if(j<n){
for( k= m-1;k>=i;--k){
spiralMatrix[k][j] = number;
number++;
}
j++;
}
}
return spiralMatrix;
}
}
Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.