Learn-dsa..in 30 days!



























CC-11 : Snake traversal of matrix elements.

Description:

Snake traversal of matrix is zigzag traversal of matrix, where 1st row is traversed left to right, 2nd row is traversed right to left, 3rd row is traversed left to right and so on, as shown in test cases below. Given input matrix mat, return the elements of mat in snake traversal order.

Test cases and expected outputs:

Input Expected outputs
mat = {
{1,2,3},
{4,5,6},
{7,8,9}};
Snake traversal : 1,2,3,6,5,4,7,8,9.
mat = {
{55,66,77,88},
{11,22,33,44},
{99,109,119,129},};
Snake traversal : 55,66,77,88,44,33,22,11,99,109,119,129.
mat = {
{30,40},
{50,60},
{70,80},
{90,100}};
Snake traversal : 30,40,60,50,70,80,100,90.
mat = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};
Snake traversal : 1,2,3,4,8,7,6,5,9,10,11,12,16,15,14,13.

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
Initialize an array named snake to hold the elements traversed using snake traversal of mat. Length of snake should be same as number of elements in mat.
Initialize a variable sIdx to hold the current index of the snake traversal array.
Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
If the row index rIdx is even, we need to traverse the row from left to right:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
Add mat[rIdx][cIdx] to snake array at index sIdx.
Increment sIdx by 1.
If the row index rIdx is odd, we need to traverse the row from right to left:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value (mat[0].length-1) and will iterate through all the matrix’s columns one by one till cIdx >= 0 by decrementing cIdx:
Add mat[rIdx][cIdx] to snake array at index sIdx.
Increment sIdx by 1.
Once above loops are completed, return array variable named snake.

Code:

public int[]  matArraySnakeTraversal(int[][] mat) throws Exception{
	int[] snake=new int[(mat.length) * (mat[0].length)];
	int sIdx=0;
    for (int rIdx=0; rIdx < mat.length; rIdx++) {
    	if (rIdx %2 == 0) {
    		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
    			snake[sIdx]=mat[rIdx][cIdx];
    			sIdx++;
    		}
    	}else {
    			for (int cIdx=(mat[0].length-1); cIdx >= 0; cIdx--) {
    			snake[sIdx]=mat[rIdx][cIdx];
    			sIdx++;
    		}
    	}
    }    
	return snake;
}

Click here to download and run code and test cases !