Printing a given matrix in Spiral form
We are given a 2D-matrix and our task is to print them in spiral from, let's see some examples.
input matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
input matrix:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
output:
1 2 3 4 5 6 7 14 21 20 19 18 17 16 15 8 9 10 11 12 13
Solution:
import java.util.Scanner;
class SpiralDemo
{
public static void printSpiral(int ar[][], int row, int col)
{
int i = 0,j = 0,k;
while(i < row && j < col)
{
//printing the first row
for(k = j; k < col; k++)
System.out.print(ar[i][k]+" ");
i++;
//printing the last column
for(k = i; k < row; k++)
System.out.print(ar[k][col-1]+" ");
col--;
//printing the last row
if(i < row)
{
for( k = col-1; k >= j; k--)
System.out.print(ar[row-1][k]+" ");
row--;
}
//printing the first column
if(j < col)
{
for(k = row-1; k >= i; k--)
System.out.print(ar[k][j]+" ");
j++;
}
}
}
public static void main(String arsgs[])
{
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int arr[][] = new int[row][col];
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
arr[i][j] = sc.nextInt();
}
}
SpiralDemo.printSpiral(arr, row, col);
}
}
class SpiralDemo
{
public static void printSpiral(int ar[][], int row, int col)
{
int i = 0,j = 0,k;
while(i < row && j < col)
{
//printing the first row
for(k = j; k < col; k++)
System.out.print(ar[i][k]+" ");
i++;
//printing the last column
for(k = i; k < row; k++)
System.out.print(ar[k][col-1]+" ");
col--;
//printing the last row
if(i < row)
{
for( k = col-1; k >= j; k--)
System.out.print(ar[row-1][k]+" ");
row--;
}
//printing the first column
if(j < col)
{
for(k = row-1; k >= i; k--)
System.out.print(ar[k][j]+" ");
j++;
}
}
}
public static void main(String arsgs[])
{
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int arr[][] = new int[row][col];
for(int i = 0; i < row; i++)
{
for(int j = 0; j < col; j++)
{
arr[i][j] = sc.nextInt();
}
}
SpiralDemo.printSpiral(arr, row, col);
}
}
No comments:
Post a Comment