Ad

Tuesday 2 July 2013

Algo#32: Generate spiral matrix or helical matrix.

It seems very easy problem of just printing 2D matrix in some format. But it includes many corner cases which needs to be taken care of. Such problems can test your coding practice.

Following is implementation of above problem in c language.





Please write comments if you find anything wrong or you want to add something more related to this topic.

1 comment:

Mamba said...

Solution in JAVA :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PrintJHelicalMatrix {

private static void print(int [][] a, int m, int n) {
System.out.println();
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++)
System.out.format("%3d ", a[i][j]);
System.out.println();
}

}

private enum Motion {
RIGHT, DOWN, LEFT, UP;
}

public static void populateMatrix(int a[][], int m, int n) {
int i = 0, j = 0, count = 1, max = m*n;
Motion mo = Motion.RIGHT;
while(count <= max) {

if(mo == Motion.RIGHT) {
if(j < n && a[i][j] == 0) {
a[i][j] = count;
j++;
count++;
}

else {
mo = Motion.DOWN;
j--;
i++;
continue;
}
}

else if(mo == Motion.DOWN) {
if(i < m && a[i][j] == 0) {
a[i][j] = count;
i++;
count++;
}

else {
mo = Motion.LEFT;
i--;
j--;
continue;
}
}

else if(mo == Motion.LEFT) {
if(j >= 0 && a[i][j] == 0) {
a[i][j] = count;
j--;
count++;
}

else {
mo = Motion.UP;
j++;
i--;
continue;
}
}

else if(mo == Motion.UP) {
if(i >=0 && a[i][j] == 0) {
a[i][j] = count;
i--;
count++;
}

else {
mo = Motion.RIGHT;
i++;
j++;
continue;
}
}

else {
System.out.println("ERROR!!\n");
}
}

}

public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
int n = Integer.parseInt(br.readLine());
int a[][] = new int[m][n];
populateMatrix(a, m, n);
print(a, m, n);
}

}

Post a Comment

Write your comment here.

Ad