Monday, October 17, 2011

printing spiral matrix in java


public class SpiralMatrix {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        int[][] a = new int[][]{ {1,2,3,4},
                                 {5,6,7,8},
                                 {9,10,11,12},
                                 {13,14,15,16}};
        
        printSpiralMatrix(a,4,4);
        
        
        String s = "sekhar";
        s.substring(s.length());
        s.substring(3, 3);
        
        try{
            String myString = "Indian";
            //myString.substring(2,10);
        }catch(Exception e){
            e.printStackTrace();
            
        }
        }

    private static void printSpiralMatrix(int[][] a, int m, int n) {
        
        // m = total number of rows = 4
        // n = total number of columns
        int k = 0; // Row starts
        int l = 0; // column starts
        
        while(k<m && l<n){
            
          //print first row....
            for(int i = l;i<n;i++){
                System.out.println(a[k][i]);
            }
            k++;
            
            for(int i=k;i<m;i++){
                System.out.println(a[i][n-1]);
            }
            
            n--;
            for(int i= n-1; i>=l;--i){
                System.out.println(a[m-1][i]);
            }
            m--;
            
            for(int i=m-1;i>=k;--i){
                System.out.println(a[i][l]);
            }
            l++;
            
            
        }
        
    }

    }

2 comments:

קคlครђ said...

import java.io.*;
class SpiralMatrix
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter an integer as order :");
int n1=Integer.parseInt(br.readLine());
int a[][]=new int[n1][n1];int c=1,n=n1;
for (int i = n-1, j = 0; i > 0; i--, j++)
{
for (int k = j; k < i; k++)
a[j][k]=c++;
for (int k = j; k < i; k++)
a[k][i]=c++;
for (int k = i; k > j; k--)
a[i][k]=c++;
for (int k = i; k > j; k--)
a[k][j]=c++;
}
//special case for middle element if N is odd
if (n % 2 == 1)
a[(n-1)/2][(n-1)/2]=c++;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
System.out.println("Made by Palash..");
}
}

Anonymous said...

this is shit..
it can't take the user input...

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...