1. Spiral traversal on matrix

1. Spiral traversal on matrix


Problem link :- click here


package progams;

import java.util.*;

public class Matrix__1
{

	static void printSpiralTraversal(int mat[][], int r, int c)
	{
		int top, bottom, left, right;
		top = 0;
		bottom = r - 1;
		left = 0;
		right = c  - 1;
		int dir = 0;
		while(left<=right && top<=bottom)
		{
			if(dir == 0)
			{
				for(int i=left; i<=right; i++)
					System.out.print(mat[top][i] + " ");
				top++;
			}
			else if(dir == 1)
			{
				for(int i=top; i<=bottom; i++)
					System.out.print(mat[i][right] + " ");
				right--;
			}
			else if(dir == 2)
			{
				for(int i=right; i>=left; i--)
					System.out.print(mat[bottom][i] + " ");
				bottom--;
			}
			else if(dir == 3)
			{
				for(int i=bottom; i>=top; i--)
					System.out.print(mat[i][left] + " ");
				left++;
			}
			dir = (dir+1) % 4;
		}
	}
	
	public static void main(String args[])
	{
		int i, j, r, c;
		
		Scanner s = new Scanner(System.in);
		System.out.print("Enter the number of rows : ");
		r = s.nextInt();
		System.out.print("Enter the numvber of columns : ");
		c = s.nextInt();
		int matrix[][] = new int[r][c];
		System.out.println("Enter the elements of the matrix : ");
		for(i=0; i<r; i++)
		{
			for(j=0; j<c; j++)
				matrix[i][j] = s.nextInt();
		}
		
		System.out.println("Given matrix :");
		printMatrix(matrix, r, c);
		System.out.println("\n\nSpural traversal : ");
		printSpiralTraversal(matrix, r, c);
	}
	
	static void printMatrix(int mat[][], int r, int c)
	{
		for(int i=0; i<r; i++)
		{
			for(int j=0; j<c; j++)
				System.out.print(mat[i][j] + "  ");
			System.out.println();
		}
	}
}

Time complexity :- O(r*c)
Space complexity :- O(r*c)


Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree