public class MatrixTopDown {

/**
* @param args
*/
public static void main(String[] args) {

int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

printArray(a);

}

public static void printArray(int[][] a) {
// print array in rectangular form
for (int i = 0; i < a.length; i++) {
matrixTraversalTopDown(a, "" + a[0][i], 0, i);
}
System.out.println("");

}

private static void matrixTraversalTopDown(int[][] inputMatrix,
String path, int row, int col) {

if (row == inputMatrix[0].length - 1) {
// Display the traversal path
System.out.println(path);
return;
}
// Botton Left
if (row + 1 = 0) {
matrixTraversalTopDown(inputMatrix, path + " - " + ""
+ inputMatrix[row + 1][col - 1], row + 1, col - 1);
}
// Bottom
if (row + 1 < inputMatrix[0].length) {
matrixTraversalTopDown(inputMatrix, path + " - " + ""
+ inputMatrix[row + 1][col], row + 1, col);
}
// Bottom Right
if (row + 1 < inputMatrix[0].length && col + 1 < inputMatrix[1].length) {
matrixTraversalTopDown(inputMatrix, path + " - " + ""
+ inputMatrix[row + 1][col + 1], row + 1, col + 1);
}
}

}

Advertisements