Skip to main content

Print matrix in snake pattern

The problem is to print the elements of a given matrix in a snake pattern. In the snake pattern, the elements are printed row by row, but for odd-numbered rows, the elements are printed in reverse order. The goal is to print the matrix elements in this snake pattern.

Example

Consider the following 4x5 matrix:

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20

The matrix elements are printed in the snake pattern as follows: 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16.

Idea to Solve the Problem

To print the matrix in a snake pattern, we can follow these steps:

  1. Define a class MyMatrix to handle matrix operations.
  2. Implement the snake_pattern function to print the matrix in a snake pattern: a. Loop through each row of the matrix: i. If the row index is even, print the elements from left to right. ii. If the row index is odd, print the elements from right to left.
  3. Print the matrix elements in the snake pattern.

Pseudocode

snake_pattern(matrix):
    rows = matrix.length
    cols = matrix[0].length
    for i in range(rows):
        if i is even:
            # Print elements from left to right
            ...
        else:
            # Print elements from right to left
            ...

matrix = {
    {1,  2,  3,  4,  5},
    {6,  7,  8,  9,  10},
    {11, 12, 13, 14, 15},
    {16, 17, 18, 19, 20}
}
obj = MyMatrix()
obj.snake_pattern(matrix)

Code Solution

/*
  C Program 
+  Print matrix in snake pattern
*/
#include<stdio.h>
#define ROW 4
#define COL 5

//print matrix elements in snake format from top to bottom
void snake_pattern(int data[ROW][COL])
{
 
  for (int i = 0; i < ROW; ++i)
  {
    if(i%2==0)
    {
      //When row is Even
      for (int j = 0; j < COL; ++j)
      {
        
        printf("%4d",data[i][j] );
        
      }
    }
    else
    {
      //When row is Odd
      for (int j = COL-1; j >= 0; --j)
      {
        
        printf("%4d",data[i][j] );
        
      }
    }

  }

  
 
 
}
int main(){
  //Define array elements
  int arr[ROW][COL]= {
    {1,  2,  3,  4,  5},
    {6,  7,  8,  9,  10}, 
    {11, 12, 13, 14, 15},
    {16, 17, 18, 19, 20}
  };

  snake_pattern(arr);

  return 0;
}

Output

   1   2   3   4   5  10   9   8   7   6  11  12  13  14  15  20  19  18  17  16
/*
  C++ Program
  Print matrix in snake pattern
*/
#include<iostream>
#define ROW 4
#define COL 5
using namespace std;

class MyMatrix {
	public:

		//print matrix elements in snake format from top to bottom
		void snake_pattern(int matrix[][COL]) {
			//Get the size of matrix
			int rows = ROW;
			int cols = COL;
			for (int i = 0; i < rows; ++i) {
				if (i % 2 == 0) {
					//When row is Even

					for (int j = 0; j < cols; ++j) {
						cout << " " << matrix[i][j];
					}
				} else {
					for (int j = cols - 1; j >= 0; --j) {
						cout << " " << matrix[i][j];
					}
				}
			}
		}
};
int main() {
	int matrix[][COL] = {
		{
			1,
			2,
			3,
			4,
			5
		},
		{
			6,
			7,
			8,
			9,
			10
		},
		{
			11,
			12,
			13,
			14,
			15
		},
		{
			16,
			17,
			18,
			19,
			20
		}
	};
	MyMatrix obj ;
	obj.snake_pattern(matrix);
	return 0;
}

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
/*
  Java Program
  Print matrix in snake pattern
*/

public class MyMatrix {

  //print matrix elements in snake format from top to bottom
  public void snake_pattern(int [][]matrix)
  {
    //Get the size of matrix
    int rows = matrix.length;
    int cols = matrix[0].length;

    for (int i = 0; i < rows; ++i)
    {
      if(i%2==0)
      {
        //When row is Even
        for (int j = 0; j < cols; ++j)
        {
          
          System.out.print(" "+matrix[i][j] );
          
        }
      }
      else
      {
        for (int j = cols-1; j >= 0; --j)
        {
          
          System.out.print(" "+matrix[i][j] );
          
        }
      }

    }
  }

  public static void main(String[] args) {
    int[][] matrix = {
      {1,  2,  3,  4,  5},
      {6,  7,  8,  9,  10}, 
      {11, 12, 13, 14, 15},
      {16, 17, 18, 19, 20}
    };
    MyMatrix obj = new MyMatrix();
  
    obj.snake_pattern(matrix);
   
  }
}

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
/*
  C# Program
  Print matrix in snake pattern
*/
using System;
public class MyMatrix {
	//print matrix elements in snake format from top to bottom
	public void snake_pattern(int[,] matrix) {
		//Get the size of matrix
		int rows = matrix.GetLength(0);
		int cols = matrix.GetLength(1);
		for (int i = 0; i < rows; ++i) {
			if (i % 2 == 0) {
				//When row is Even

				for (int j = 0; j < cols; ++j) {
					Console.Write(" " + matrix[i,j]);
				}
			} else {
				for (int j = cols - 1; j >= 0; --j) {
					Console.Write(" " + matrix[i,j]);
				}
			}
		}
	}
	public static void Main(String[] args) {
		int[,] matrix = {
			{
				1,
				2,
				3,
				4,
				5
			},
			{
				6,
				7,
				8,
				9,
				10
			},
			{
				11,
				12,
				13,
				14,
				15
			},
			{
				16,
				17,
				18,
				19,
				20
			}
		};
		MyMatrix obj = new MyMatrix();
		obj.snake_pattern(matrix);
	}
}

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
<?php
/*
  Php Program
  Print matrix in snake pattern
*/
class MyMatrix {
	//print matrix elements in snake format from top to bottom

	public 	function snake_pattern($matrix) {
		//Get the size of matrix
		$rows = count($matrix);
		$cols = count($matrix[0]);
		for ($i = 0; $i < $rows; ++$i) {
			if ($i % 2 == 0) {
				//When row is Even

				for ($j = 0; $j < $cols; ++$j) {
					echo(" ". $matrix[$i][$j]);
				}
			} else {
				for ($j = $cols - 1; $j >= 0; --$j) {
					echo(" ". $matrix[$i][$j]);
				}
			}
		}
	}
}

function main() {
	$matrix = array(array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10), array(11, 12, 13, 14, 15), array(16, 17, 18, 19, 20));
	$obj = new MyMatrix();
	$obj->snake_pattern($matrix);

}
main();

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
/*
  Node Js Program
  Print matrix in snake pattern
*/
class MyMatrix {
	//print matrix elements in snake format from top to bottom
	snake_pattern(matrix) {
		//Get the size of matrix
		var rows = matrix.length;
		var cols = matrix[0].length;
		for (var i = 0; i < rows; ++i) {
			if (i % 2 == 0) {
				//When row is Even

				for (var j = 0; j < cols; ++j) {
					process.stdout.write(" " + matrix[i][j]);
				}
			} else {
				for (var j = cols - 1; j >= 0; --j) {
					process.stdout.write(" " + matrix[i][j]);
				}
			}
		}
	}
}

function main(args) {
	var matrix = [
		[1, 2, 3, 4, 5],
		[6, 7, 8, 9, 10],
		[11, 12, 13, 14, 15],
		[16, 17, 18, 19, 20]
	];
	var obj = new MyMatrix();
	obj.snake_pattern(matrix);
}

main();

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
# Python 3 Program
# Print matrix in snake pattern
class MyMatrix :
	# print matrix elements in snake format from top to bottom
	def snake_pattern(self, matrix) :
		rows = len(matrix)
		cols = len(matrix[0])
		i = 0
		j = 0
		while (i < rows) :
			if (i % 2 == 0) :
				# When row is Even
				j = 0
				while (j < cols) :
					print(" ", matrix[i][j], end = "")
					j += 1
				
			else :
				j = cols - 1
				while (j >= 0) :
					print(" ", matrix[i][j], end = "")
					j -= 1
				
			
			i += 1
		
	

def main() :
	matrix = [
		[1, 2, 3, 4, 5],
		[6, 7, 8, 9, 10],
		[11, 12, 13, 14, 15],
		[16, 17, 18, 19, 20]
	]
	obj = MyMatrix()
	obj.snake_pattern(matrix)


if __name__ == "__main__":
	main()

Output

  1  2  3  4  5  10  9  8  7  6  11  12  13  14  15  20  19  18  17  16
# Ruby Program
# Print matrix in snake pattern
class MyMatrix 
	# print matrix elements in snake format from top to bottom
	def snake_pattern(matrix) 
		rows = matrix.length
		cols = matrix[0].length
		i = 0
		j = 0
		while (i < rows) 
			if (i % 2 == 0) 
				# When row is Even
				j = 0
				while (j < cols) 
					print(" ", matrix[i][j])
					j += 1
				end
			else 
				j = cols - 1
				while (j >= 0) 
					print(" ", matrix[i][j])
					j -= 1
				end
			end
			i += 1
		end
	end
end
def main() 
	matrix = [
		[1, 2, 3, 4, 5],
		[6, 7, 8, 9, 10],
		[11, 12, 13, 14, 15],
		[16, 17, 18, 19, 20]
	]
	obj = MyMatrix.new()
	obj.snake_pattern(matrix)
end
main()

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
/*
  Scala Program
  Print matrix in snake pattern
*/
class MyMatrix {
	//print matrix elements in snake format from top to bottom
	def snake_pattern(matrix: Array[Array[Int]]): Unit = {
		val rows: Int = matrix.length;
		val cols: Int = matrix(0).length;
		var i: Int = 0;
		var j: Int = 0;
		while (i < rows) {
			if (i % 2 == 0) {
				//When row is Even
				j = 0;
				while (j < cols) {
					print(" " + matrix(i)(j));
					j += 1;
				}
			} else {
				j = cols - 1;
				while (j >= 0) {
					print(" " + matrix(i)(j));
					j -= 1;
				}
			}
			i += 1;
		}
	}
}
object Main {
	def main(args: Array[String]): Unit = {
		val matrix: Array[Array[Int]] = Array(
			Array(1, 2, 3, 4, 5),
			Array(6, 7, 8, 9, 10),
			Array(11, 12, 13, 14, 15),
			Array(16, 17, 18, 19, 20));
		val obj: MyMatrix = new MyMatrix();
		obj.snake_pattern(matrix);
	}
}

Output

 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
/*
  Swift Program
  Print matrix in snake pattern
*/
class MyMatrix {
	//print matrix elements in snake format from top to bottom
	func snake_pattern(_ matrix: [
		[Int]
	]) {
		let rows: Int = matrix.count;
		let cols: Int = matrix[0].count;
		var i: Int = 0;
		var j: Int = 0;
		while (i < rows) {
			if (i % 2 == 0) {
				//When row is Even
				j = 0;
				while (j < cols) {
					print(" ", matrix[i][j], terminator: "");
					j += 1;
				}
			} else {
				j = cols - 1;
				while (j >= 0) {
					print(" ", matrix[i][j], terminator: "");
					j -= 1;
				}
			}
			i += 1;
		}
	}
}
func main() {
	let matrix: [
		[Int]
	] = [
		[1, 2, 3, 4, 5],
		[6, 7, 8, 9, 10],
		[11, 12, 13, 14, 15],
		[16, 17, 18, 19, 20]
	];
	let obj: MyMatrix = MyMatrix();
	obj.snake_pattern(matrix);
}
main();

Output

  1  2  3  4  5  10  9  8  7  6  11  12  13  14  15  20  19  18  17  16

Output Explanation

The mentioned Java code correctly implements the above algorithm to print the matrix elements in a snake pattern. It checks the row index and prints the elements from left to right for even rows and from right to left for odd rows. The output matches the expected snake pattern of the given matrix.

Time Complexity

The time complexity of the mentioned solution is O(N), where N is the number of elements in the matrix. The snake_pattern function iterates through each element of the matrix exactly once, printing the elements in the desired snake pattern. Therefore, the overall time complexity is O(N).





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment