Write a program to print Spiral Matrix
Example 1:
Input: n=3 // 3*3
Output1 2 38 9 47 6 5
Approach:
Java
public class MatrixSpiral {public static void main(String[] args) {// number of col, rowint n = 3;// create spiral matrixint spiral[][] = generateMatrix(n);// print matrixprintMatrix(spiral);}private static void printMatrix(int[][] matrixA) {for (int i = 0; i < matrixA.length; i++) {for (int j = 0; j < matrixA.length; j++) {System.out.print(matrixA[i][j] + " ");}System.out.println();}}public static int[][] generateMatrix(int n) {int a[][] = new int[n][n];int seq = 0;int i = 0;int num = n;int count = 0;for (int j = count; j < (num - count); j++) {i = count;a[i][j] = ++seq;if (j == (n + count - 1)) {i = i + 1;n = n - 1;if (n == 0)break;for (int k = 0; k < n; k++) {a[i][j] = ++seq;i = i + 1;}i = i - 1;j = j - 1;for (int k = (n - 1); k >= 0; k--) {a[i][j] = ++seq;j = j - 1;}j = j + 1;n = n - 1;i = i - 1;for (int k = (n - 1); k >= 0; k--) {a[i][j] = ++seq;i = i - 1;}count = count + 1;}if (n == 0)break;}return a;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the spiral//matrix of dimension n*nvector<vector<int>> spiralMatrix(int n){//value of the matrix from 1 to n*nint i=1;int k=0,l=0;int it;int m=n;//matrix for final output//initialize with 0vector<vector<int>> matrix( m , vector<int> (n, 0));//iterate till the end of rows and//columswhile(k<m&&l<n){// get first row from the remaining//rows of the matrixfor(it=l;it<n;it++){matrix[k][it]=i;//increment to next valuei++;}//increment row count from top//to downk++;//generate the last column from//the remaining columnsfor(it=k;it<m;it++){matrix[it][n-1]=i;//increment for next valuei++;}//decrement no of rowsn--;//if their are rows remaingif(k<m){//generate the last row from the remaning//rowsfor(it=n-1;it>=l;it--){matrix[m-1][it]=i;i++;}//decremenr no of columsm--;}//if thier is any columnif(l<n){//generate the first column//from the remaining columnsfor(it=m-1;it>=k;it--){matrix[it][l]=i;i++;}l++;}}//return the final resultreturn matrix;}//function to print the matrixvoid printMatrix(vector<vector<int>> matrix){//dimension of square matrixint n=matrix.size();//iterate till end of rowsfor(int i=0;i<n;i++){//iterate till end of columnsfor(int j=0;j<n;j++){//print the current cell valuecout<<matrix[i][j]<<" ";}cout<<"\n";}}int main(){// number of col, rowint n = 3;// create spiral matrixvector<vector<int>> spiral = spiralMatrix(n);// print matrixprintMatrix(spiral);}
No comments:
Post a Comment