Thursday, 4 September 2014

Spiral Matrix : Java : BlueJ

Objective:


The Program Prints the Matrix which forms a Spiral Pattern with Consecutive Integers till the Square of the order of Matrix.
BlueJ Program Screenshot:






Java Program Source Code:

/**
 * The Program prints the array in a Spiral Order.
 * @author SHANTANU KHAN
 * @mail shantanukhan@live.com
 * @website 0code.blogspot.com 
 * Program Type : BlueJ Program - Java
 */
import java.io.*;
public class SpiralMatrix
{
    private int[][]m;
    private int order;
    public SpiralMatrix(int o)
    {
        m=new int[order=o][order=o];
    }
    public void fill()
    {
        int end=order;
        int st=0;
        int p=1;
        int q=0;
        int rear=1;
        while(p<=order*order){
            for(int i=st; i<end; i++){
                m[q][i]=p++;
            }
            for(int i=st+1; i<end; i++){
                m[i][end-rear]=p++;
            }
            for(int i=end-2; i>=st; i--){
                m[end-rear][i]=p++;
            }
            st++;
            for(int i=end-2; i>=st; i--){
                m[i][q]=p++;
            }
            end--;
            q++;
        }
    }
    public String setw(int num)
    {
        String s=new String()+num;
        int pad=3-s.length();
        while(pad-->0){
            s=" "+s;
        }
        return s;
    }
    public void print()
    {
        System.out.println("The spiral matrix is:");
        for(int i=0; i<order; i++){
            for(int j=0; j<order; j++){
                System.out.print(setw(m[i][j])+" ");        
            }
            System.out.println();
        }
    }
    public static void main(String[]args)throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print(" Enter order of SPIRAL MATRIX : ");
        int d=Integer.parseInt(br.readLine());
        System.out.println();
        SpiralMatrix obj=new SpiralMatrix(d);
        obj.fill();
        obj.print();
    }
}
/////////////////////////////////////////////////////////////////////
////////////http://0code.blogspot.in/////////////////////////////////

0 comments :

Post a Comment