Skip to main content

Rotate middle diamond element in matrix by anticlockwise

The problem is to rotate the middle diamond elements in a square matrix anticlockwise. The diamond elements are the central elements of the matrix that form a diamond shape. The task is to rotate these elements anticlockwise by one position within the diamond shape.

Example

Consider the following 5x5 matrix:

1  2   3  4  5
6  -7  8  2  10
2  12 13 15  16
17 2  19 20  21
22 23 24 25  2

After rotating the middle diamond elements anticlockwise by one position, the matrix becomes:


        3
    -7  8  2
2  12  13  15  16
    2  19  20
        24

        2
    3  15  16
-7  8  13  19  20
    2  12  24
        2

Idea to Solve the Problem

To rotate the middle diamond elements in the matrix anticlockwise, we can follow these steps:

  1. Define a class MyMatrix to handle matrix operations.
  2. Implement the rotate_element function to rotate the diamond elements in a square matrix anticlockwise: a. Calculate the middle column and middle row of the diamond. b. Traverse the four edges of the diamond and rotate the elements in an anticlockwise manner. c. Perform the rotation by swapping elements and using temporary variables. d. Recursively call the rotate_element function for the inner diamond, if applicable.
  3. Implement the rotate function to check if the matrix is a valid square matrix with an odd number of rows and columns. If it is, calculate the number of diamond elements and call the rotate_element function.
  4. Display the matrix before and after the rotation using the diamond_view function.

Pseudocode

rotate_element(matrix, s_row, s_col, e_row, e_col, k):
    mid_col = s_col + ((e_col - s_col) / 2)
    mid_row = mid_col
    back = matrix[s_row][mid_col]
    for i from mid_col - 1 to s_col:
        # Rotate left edge
        ...
    for i from s_col + 1 to mid_col:
        # Rotate top edge
        ...
    for i from mid_col + 1 to e_col:
        # Rotate right edge
        ...
    for i from e_col - 1 to mid_col:
        # Rotate bottom edge
        ...
    if s_row + 1 <= e_row - 1 and k > 0:
        # Recursive call
        rotate_element(matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k)

rotate(matrix):
    if matrix is not a valid square matrix with odd size:
        return
    size = calculate number of diamond elements
    rotate_element(matrix, 0, 0, rows - 1, cols - 1, size)

show(matrix, row, col):
    print elements in a row

diamond_view(matrix):
    print matrix in diamond view format

matrix = {
    {1,  2,  3,  4,  5},
    {6,  -7, 8,  2,  10},
    {2,  12, 13, 15,  16},
    {17, 2,  19, 20,  21},
    {22, 23, 24, 25,  2}
}
obj = MyMatrix(matrix)
obj.diamond_view(matrix)
obj.rotate(matrix)
obj.diamond_view(matrix)

Code Solution

/*
  C Program 
  Rotate middle diamond element in matrix by anticlockwise
*/
#include<stdio.h>
#define ROW 5
#define COL 5

//Rotate diamond element in square matrix anticlockwise
void rotate_element(int matrix[ROW][COL],
  int s_row,
  int s_col,
  int e_row,
  int e_col,
  int k)
{

  //Calculate middle column in matrix
  int mid_col = s_col + ((e_col - s_col)/2);

  //Calculate middle row in matrix
  int mid_row = mid_col;

  int back=matrix[s_row][mid_col],current=0;

  for (int i = mid_col-1,j=1; i >= s_col && k > 0 ; --i,k--,j++)
  {
    current = matrix[s_row+j][i];

    matrix[s_row+j][i] = back ;

    back=current;
  }

  for (int i = s_col+1,j=1; i <= mid_col && k > 0 ; ++i,k--,j++)
  {
    current  = matrix[(mid_row)+j][i];
    matrix[(mid_row)+j][i] = back ;
    back=current;
  }



  for (int i = mid_col+1,j=1; i <= e_col && k > 0 ; ++i,k--,j++)
  {

    current = matrix[e_row-j][i];
    matrix[e_row-j][i] = back ;
    back=current;
  }
  
  for (int i = e_col-1,j=1; i >= mid_col && k > 0 ; --i,k--,j++)
  {
   
    current = matrix[(mid_row)-j][i] ;
    matrix[(mid_row)-j][i]= back ;
    back=current;
  }
  

  if(s_row+1 <= e_row-1 && k > 0)
  {
    //Recursive call
    rotate_element(matrix, s_row+1, s_col+1, e_row-1, e_col-1, k);
  }
  
    
}
//Count number of diamond element
int element_size(int col)
{
  int counter=0;

  while(col>0)
  {
    counter+=col;
    col--;
  }
  return counter*4;

}
void rotate(int matrix[ROW][COL])
{
  if(ROW != COL || COL % 2 == 0)
  {
    printf("\nNot a valid perfect Odd square matrix");
    return;
  }
  int size=element_size((COL)/2)+1;

  rotate_element(matrix, 0, 0, ROW-1, COL-1, size);


}

void show(int arr[ROW][COL],int row,int col)
{
  for (int i = col; i < (COL)-col; ++i)
  {
    printf("%3d",arr[row][i] );
  }
}
void space(int size)
{
  for (int i = 0; i <= size; ++i)
  {
    printf(" ");
  }
}
void diamond_view(int arr[ROW][COL])
{
  if(ROW != COL || COL%2==0)
  {
    printf("\nNot a valid perfect Odd square matrix");
    return;
  }

  int col = COL / 2;
  int counter = col*3;
  int distance = 3;
  for (int i = 0; i < ROW; ++i)
  {
    space(counter);
    show(arr,i,col);
    
    if(i < ROW/2)
    {
      counter -= distance;
      col--;
    }
    else
    { 
      col++;
      counter += distance;
    }

    printf("\n");
  }

}
int main(){

  //Define matrix element
  int matrix[ROW][COL] ={
    {1,  2,   3,  4,  5},
    {6,  -7,  8,  2,  10},
    {2, 12, 13, 15,  16},
    {17, 2, 19, 20,  21},
    {22, 23, 24, 25,  2}

  }; 
  diamond_view(matrix);
  rotate(matrix);
  diamond_view(matrix);


  return 0;
}

Output

         3
     -7  8  2
   2 12 13 15 16
      2 19 20
        24
         2
      3 15 16
  -7  8 13 19 20
      2 12 24
         2
/*
  C++ Program
  Rotate middle diamond element in matrix by anticlockwise
*/
#include<iostream>
#define ROW 5
#define COL 5
using namespace std;


class MyMatrix {
  public:
    int rows;
  int cols;
  MyMatrix() {
    //Get the size of matrix
    this->rows = ROW;
    this->cols = COL;
  }
  //Rotate diamond element in square matrix anticlockwise
  void rotate_element(int matrix[][COL], int s_row, int s_col, int e_row, int e_col, int k) {
    //Calculate middle column in matrix
    int mid_col = s_col + ((e_col - s_col) / 2);
    //Calculate middle row in matrix
    int mid_row = mid_col;
    int back = matrix[s_row][mid_col], current = 0;
    
    for (int i = mid_col-1,j=1; i >= s_col && k > 0 ; --i,k--,j++)
    {
      current = matrix[s_row+j][i];

      matrix[s_row+j][i] = back ;

      back=current;
    }

    for (int i = s_col+1,j=1; i <= mid_col && k > 0 ; ++i,k--,j++)
    {
      current  = matrix[(mid_row)+j][i];
      matrix[(mid_row)+j][i] = back ;
      back=current;
    }



    for (int i = mid_col+1,j=1; i <= e_col && k > 0 ; ++i,k--,j++)
    {

      current = matrix[e_row-j][i];
      matrix[e_row-j][i] = back ;
      back=current;
    }
    
    for (int i = e_col-1,j=1; i >= mid_col && k > 0 ; --i,k--,j++)
    {
     
      current = matrix[(mid_row)-j][i] ;
      matrix[(mid_row)-j][i]= back ;
      back=current;
    }
    

    if(s_row+1 <= e_row-1 && k > 0)
    {
      //Recursive call
      rotate_element(matrix, s_row+1, s_col+1, e_row-1, e_col-1, k);
    }
  }
  //Count number of diamond element
  int element_size(int col) {
    int counter = 0;
    while (col > 0) {
      counter += col;
      col--;
    }
    return counter *4;
  }
  void rotate(int matrix[][COL]) {
    if (this->rows != this->cols || this->cols % 2 == 0) {
      cout << "\nNot a valid perfect Odd square matrix";
      return;
    }
    int size = this->element_size((this->cols) / 2) + 1;
    this->rotate_element(matrix, 0, 0, this->rows - 1, this->cols - 1, size);
  }
  void show(int matrix[][COL], int row, int col) {
    for (int i = col; i < (this->cols) - col; ++i) {
      cout << " " << matrix[row][i] << " ";
    }
  }
  void space(int size) {
    for (int i = 0; i <= size; ++i) {
      cout << " ";
    }
  }
  void diamond_view(int matrix[][COL]) {
    if (this->rows != this->cols || this->cols % 2 == 0) {
      cout << "\nNot a valid perfect Odd square matrix";
      return;
    }
    int col = this->cols / 2;
    int counter = col *3;
    int distance = 3;
    for (int i = 0; i < this->rows; ++i) {
      this->space(counter);
      this->show(matrix, i, col);
      if (i < this->rows / 2) {
        counter -= distance;
        col--;
      } else {
        col++;
        counter += distance;
      }
      cout << "\n";
    }
  }
};
int main() {
  int matrix[][COL] = {
    {
      1,
      2,
      3,
      4,
      5
    },
    {
      6,
      -7,
      8,
      2,
      10
    },
    {
      2,
      12,
      13,
      15,
      16
    },
    {
      17,
      2,
      19,
      20,
      21
    },
    {
      22,
      23,
      24,
      25,
      2
    }
  };
  MyMatrix obj ;
  obj.diamond_view(matrix);
  obj.rotate(matrix);
  obj.diamond_view(matrix);
  return 0;
}

Output

        3
     -7  8  2
  2  12  13  15  16
     2  19  20
        24
        2
     3  15  16
  -7  8  13  19  20
     2  12  24
        2
/*
  Java Program
  Rotate middle diamond element in matrix by anticlockwise
*/
public class MyMatrix {

  public int rows;
  public int cols;
  public MyMatrix(int [][]matrix)
  {
    //Get the size of matrix
    this.rows = matrix.length;
    this.cols = matrix[0].length;
  }
  //Rotate diamond element in square matrix anticlockwise
  public void rotate_element(int [][]matrix,
    int s_row,
    int s_col,
    int e_row,
    int e_col,
    int k)
  {

    //Calculate middle column in matrix
    int mid_col = s_col + ((e_col - s_col)/2);

    //Calculate middle row in matrix
    int mid_row = mid_col;

    int back=matrix[s_row][mid_col],current=0;

    for (int i = mid_col-1,j=1; i >= s_col && k > 0 ; --i,k--,j++)
    {
      current = matrix[s_row+j][i];

      matrix[s_row+j][i] = back ;

      back=current;
    }

    for (int i = s_col+1,j=1; i <= mid_col && k > 0 ; ++i,k--,j++)
    {
      current  = matrix[(mid_row)+j][i];
      matrix[(mid_row)+j][i] = back ;
      back=current;
    }



    for (int i = mid_col+1,j=1; i <= e_col && k > 0 ; ++i,k--,j++)
    {

      current = matrix[e_row-j][i];
      matrix[e_row-j][i] = back ;
      back=current;
    }
    
    for (int i = e_col-1,j=1; i >= mid_col && k > 0 ; --i,k--,j++)
    {
     
      current = matrix[(mid_row)-j][i] ;
      matrix[(mid_row)-j][i]= back ;
      back=current;
    }
    

    if(s_row+1 <= e_row-1 && k > 0)
    {
      //Recursive call
      rotate_element(matrix, s_row+1, s_col+1, e_row-1, e_col-1, k);
    }
      
      
  }
  //Count number of diamond element
  public int element_size(int col)
  {
    int counter=0;

    while(col>0)
    {
      counter+=col;
      col--;
    }
    return counter*4;

  }
  public void rotate(int [][]matrix)
  {
    if(this.rows != this.cols || this.cols % 2 == 0)
    {
      System.out.print("\nNot a valid perfect Odd square matrix");
      return;
    }
    int size=element_size((this.cols)/2)+1;

    rotate_element(matrix, 0, 0, this.rows-1, this.cols-1, size);


  }

  public void show(int [][]matrix,int row,int col)
  {
    for (int i = col; i < (this.cols)-col; ++i)
    {
      System.out.print(" "+matrix[row][i] +" ");
    }
  }
  public void space(int size)
  {
    for (int i = 0; i <= size; ++i)
    {
      System.out.print(" ");
    }
  }
  public void diamond_view(int [][]matrix)
  {
    if(this.rows != this.cols || this.cols%2==0)
    {
      System.out.print("\nNot a valid perfect Odd square matrix");
      return;
    }

    int col = this.cols / 2;
    int counter = col*3;
    int distance = 3;
    for (int i = 0; i < this.rows; ++i)
    {
      space(counter);
      show(matrix,i,col);
      
      if(i < this.rows/2)
      {
        counter -= distance;
        col--;
      }
      else
      { 
        col++;
        counter += distance;
      }

      System.out.print("\n");
    }

  }

  public static void main(String[] args) 
  {
    //Define matrix element
    int [][]matrix={
      {1,  2,   3,  4,  5},
      {6,  -7,  8,  2,  10},
      {2, 12, 13, 15,  16},
      {17, 2, 19, 20,  21},
      {22, 23, 24, 25,  2}

    }; 
    MyMatrix obj = new MyMatrix(matrix);
    obj.diamond_view(matrix);
    obj.rotate(matrix);
    obj.diamond_view(matrix);

  }
}

Output

        3
     -7  8  2
  2  12  13  15  16
     2  19  20
        24
        2
     3  15  16
  -7  8  13  19  20
     2  12  24
        2
using System;

/*
  C# Program
  Rotate middle diamond element in matrix by anticlockwise
*/

public class MyMatrix {
	int rows;
	int cols;
	MyMatrix(int[,] matrix) {
		//Get the size of matrix
		this.rows = matrix.GetLength(0);
		this.cols = matrix.GetLength(1);
	}
	//Rotate diamond element in square matrix anticlockwise
	public void rotate_element(int[,] matrix, int s_row, int s_col, int e_row, int e_col, int k) {
		//Calculate middle column in matrix
		int mid_col = s_col + ((e_col - s_col) / 2);
		//Calculate middle row in matrix
		int mid_row = mid_col;
		int back = matrix[s_row,mid_col], current = 0;
		for (int i = mid_col - 1, j = 1; i >= s_col && k > 0; --i, k--, j++) {
			current = matrix[s_row + j,i];
			matrix[s_row + j,i] = back;
			back = current;
		}
		for (int i = s_col + 1, j = 1; i <= mid_col && k > 0; ++i, k--, j++) {
			current = matrix[(mid_row) + j,i];
			matrix[(mid_row) + j,i] = back;
			back = current;
		}
		for (int i = mid_col + 1, j = 1; i <= e_col && k > 0; ++i, k--, j++) {
			current = matrix[e_row - j,i];
			matrix[e_row - j,i] = back;
			back = current;
		}
		for (int i = e_col - 1, j = 1; i >= mid_col && k > 0; --i, k--, j++) {
			current = matrix[(mid_row) - j,i];
			matrix[(mid_row) - j,i] = back;
			back = current;
		}
		if (s_row + 1 <= e_row - 1 && k > 0) {
			rotate_element(matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k);
		}
	}
	//Count number of diamond element
	public int element_size(int col) {
		int counter = 0;
		while (col > 0) {
			counter += col;
			col--;
		}
		return counter * 4;
	}
	public void rotate(int[,] matrix) {
		if (this.rows != this.cols || this.cols % 2 == 0) {
			Console.Write("\nNot a valid perfect Odd square matrix");
			return;
		}
		int size = element_size((this.cols) / 2) + 1;
		rotate_element(matrix, 0, 0, this.rows - 1, this.cols - 1, size);
	}
	public void show(int[,] matrix, int row, int col) {
		for (int i = col; i < (this.cols) - col; ++i) {
			Console.Write(" " + matrix[row,i] + " ");
		}
	}
	public void space(int size) {
		for (int i = 0; i <= size; ++i) {
			Console.Write(" ");
		}
	}
	public void diamond_view(int[,] matrix) {
		if (this.rows != this.cols || this.cols % 2 == 0) {
			Console.Write("\nNot a valid perfect Odd square matrix");
			return;
		}
		int col = this.cols / 2;
		int counter = col * 3;
		int distance = 3;
		for (int i = 0; i < this.rows; ++i) {
			space(counter);
			show(matrix, i, col);
			if (i < this.rows / 2) {
				counter -= distance;
				col--;
			} else {
				col++;
				counter += distance;
			}
			Console.Write("\n");
		}
	}
	public static void Main(String[] args) {
		int[,]
		//Define matrix element
		matrix = {
			{
				1,
				2,
				3,
				4,
				5
			},
			{
				6,
				-7,
				8,
				2,
				10
			},
			{
				2,
				12,
				13,
				15,
				16
			},
			{
				17,
				2,
				19,
				20,
				21
			},
			{
				22,
				23,
				24,
				25,
				2
			}
		};
		MyMatrix obj = new MyMatrix(matrix);
		obj.diamond_view(matrix);
		obj.rotate(matrix);
		obj.diamond_view(matrix);
	}
}

Output

        3
     -7  8  2
  2  12  13  15  16
     2  19  20
        24
        2
     3  15  16
  -7  8  13  19  20
     2  12  24
        2
<?php
/*
  Php Program
  Rotate middle diamond element in matrix by anticlockwise
*/
class MyMatrix {
	public $rows;
	public $cols;

	function __construct($matrix) {
		//Get the size of matrix
		$this->rows = count($matrix);
		$this->cols = count($matrix[0]);
	}
	//Rotate diamond element in square matrix anticlockwise

	public 	function rotate_element(&$matrix, $s_row, $s_col, $e_row, $e_col, $k) {
		//Calculate middle column in matrix
		$mid_col = $s_col + (intval(($e_col - $s_col) / 2));
		//Calculate middle row in matrix
		$mid_row = $mid_col;
		$back = $matrix[$s_row][$mid_col];
		$current = 0;
		for ($i = $mid_col - 1, $j = 1; $i >= $s_col && $k > 0; --$i, $k--, $j++) {
			$current = $matrix[$s_row + $j][$i];
			$matrix[$s_row + $j][$i] = $back;
			$back = $current;
		}
		for ($i = $s_col + 1, $j = 1; $i <= $mid_col && $k > 0; ++$i, $k--, $j++) {
			$current = $matrix[($mid_row) + $j][$i];
			$matrix[($mid_row) + $j][$i] = $back;
			$back = $current;
		}
		for ($i = $mid_col + 1, $j = 1; $i <= $e_col && $k > 0; ++$i, $k--, $j++) {
			$current = $matrix[$e_row - $j][$i];
			$matrix[$e_row - $j][$i] = $back;
			$back = $current;
		}
		for ($i = $e_col - 1, $j = 1; $i >= $mid_col && $k > 0; --$i, $k--, $j++) {
			$current = $matrix[($mid_row) - $j][$i];
			$matrix[($mid_row) - $j][$i] = $back;
			$back = $current;
		}
		if ($s_row + 1 <= $e_row - 1 && $k > 0) {
			//Recursive call
			$this->rotate_element($matrix, $s_row + 1, $s_col + 1, $e_row - 1, $e_col - 1, $k);
		}
	}
	//Count number of diamond element

	public 	function element_size($col) {
		$counter = 0;
		while ($col > 0) {
			$counter += $col;
			$col--;
		}
		return $counter *4;
	}
	public 	function rotate(&$matrix) {
		if ($this->rows != $this->cols || $this->cols % 2 == 0) {
			echo("\nNot a valid perfect Odd square matrix");
			return;
		}
		$size = $this->element_size(intval(($this->cols) / 2)) + 1;
		$this->rotate_element($matrix, 0, 0, $this->rows - 1, $this->cols - 1, $size);
	}
	public 	function show($matrix, $row, $col) {
		for ($i = $col; $i < ($this->cols) - $col; ++$i) {
			echo(" ". $matrix[$row][$i] ." ");
		}
	}
	public 	function space($size) {
		for ($i = 0; $i <= $size; ++$i) {
			echo(" ");
		}
	}
	public 	function diamond_view($matrix) {
		if ($this->rows != $this->cols || $this->cols % 2 == 0) {
			echo("\nNot a valid perfect Odd square matrix");
			return;
		}
		$col = intval($this->cols / 2);
		$counter = $col *3;
		$distance = 3;
		for ($i = 0; $i < $this->rows; ++$i) {
			$this->space($counter);
			$this->show($matrix, $i, $col);
			if ($i < intval($this->rows / 2)) {
				$counter -= $distance;
				$col--;
			} else {
				$col++;
				$counter += $distance;
			}
			echo("\n");
		}
	}
}

function main() {
	//Define matrix element
	$matrix = array(
      array(1, 2, 3, 4, 5), 
      array(6, -7, 8, 2, 10), 
      array(2, 12, 13, 15, 16), 
      array(17, 2, 19, 20, 21), 
      array(22, 23, 24, 25, 2));
	$obj = new MyMatrix($matrix);
	$obj->diamond_view($matrix);
	$obj->rotate($matrix);
	$obj->diamond_view($matrix);

}
main();

Output

        3
     -7  8  2
  2  12  13  15  16
     2  19  20
        24
        2
     3  15  16
  -7  8  13  19  20
     2  12  24
        2
/*
  Node Js Program
  Rotate middle diamond element in matrix by anticlockwise
*/
class MyMatrix {
	constructor(matrix) {
		//Get the size of matrix
		this.rows = matrix.length;
		this.cols = matrix[0].length;
	}

	//Rotate diamond element in square matrix anticlockwise
	rotate_element(matrix, s_row, s_col, e_row, e_col, k) {
		//Calculate middle column in matrix
		var mid_col = s_col + (parseInt((e_col - s_col) / 2));
		//Calculate middle row in matrix
		var mid_row = mid_col;
		var back = matrix[s_row][mid_col];
		var current = 0;
		for (var i = mid_col - 1,j = 1; i >= s_col && k > 0; --i, k--, j++) {
			current = matrix[s_row + j][i];
			matrix[s_row + j][i] = back;
			back = current;
		}

		for (var i = s_col + 1, j = 1; i <= mid_col && k > 0; ++i, k--, j++) {
			current = matrix[(mid_row) + j][i];
			matrix[(mid_row) + j][i] = back;
			back = current;
		}

		for (var i = mid_col + 1, j = 1; i <= e_col && k > 0; ++i, k--, j++) {
			current = matrix[e_row - j][i];
			matrix[e_row - j][i] = back;
			back = current;
		}

		for (var i = e_col - 1, j = 1; i >= mid_col && k > 0; --i, k--, j++) {
			current = matrix[(mid_row) - j][i];
			matrix[(mid_row) - j][i] = back;
			back = current;
		}

		if (s_row + 1 <= e_row - 1 && k > 0) {
			//Recursive call
			this.rotate_element(matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k);
		}
	}

	//Count number of diamond element
	element_size(col) {
		var counter = 0;
		while (col > 0) {
			counter += col;
			col--;
		}

		return counter *4;
	}
	rotate(matrix) {
		if (this.rows != this.cols || this.cols % 2 == 0) {
			process.stdout.write("\nNot a valid perfect Odd square matrix");
			return;
		}
		var size = this.element_size(parseInt((this.cols) / 2)) + 1;
		this.rotate_element(matrix, 0, 0, this.rows - 1, this.cols - 1, size);
	}
	show(matrix, row, col) {
		for (var i = col; i < (this.cols) - col; ++i) {
			process.stdout.write(" " + matrix[row][i] + " ");
		}
	}
	space(size) {
		for (var i = 0; i <= size; ++i) {
			process.stdout.write(" ");
		}
	}
	diamond_view(matrix) {
		if (this.rows != this.cols || this.cols % 2 == 0) {
			process.stdout.write("\nNot a valid perfect Odd square matrix");
			return;
		}
		var col = parseInt(this.cols / 2);
		var counter = col *3;
		var distance = 3;
		for (var i = 0; i < this.rows; ++i) {
			this.space(counter);
			this.show(matrix, i, col);
			if (i < parseInt(this.rows / 2)) {
				counter -= distance;
				col--;
			} else {
				col++;
				counter += distance;
			}

			process.stdout.write("\n");
		}
	}
}

function main(args) {
	//Define matrix element
	var matrix = [
		[1, 2, 3, 4, 5],
		[6, -7, 8, 2, 10],
		[2, 12, 13, 15, 16],
		[17, 2, 19, 20, 21],
		[22, 23, 24, 25, 2]
	];
	var obj = new MyMatrix(matrix);
	obj.diamond_view(matrix);
	obj.rotate(matrix);
	obj.diamond_view(matrix);
}

main();

Output

        3
     -7  8  2
  2  12  13  15  16
     2  19  20
        24
        2
     3  15  16
  -7  8  13  19  20
     2  12  24
        2
#   Python 3 Program
#   Rotate middle diamond element in matrix by anticlockwise
class MyMatrix :
	
	def __init__(self, matrix) :
		# Get the size of matrix
		self.rows = len(matrix)
		self.cols = len(matrix[0])
	
	# Rotate diamond element in square matrix anticlockwise
	def rotate_element(self, matrix, s_row, s_col, e_row, e_col, k) :
		mid_col = s_col + (int((e_col - s_col) / 2))
		mid_row = mid_col
		back = matrix[s_row][mid_col]
		current = 0
		i = mid_col - 1
		j = 1
		while (i >= s_col and k > 0) :
			current = matrix[s_row + j][i]
			matrix[s_row + j][i] = back
			back = current
			i -= 1
			k -= 1
			j += 1
		
		i = s_col + 1
		j = 1
		while (i <= mid_col and k > 0) :
			current = matrix[(mid_row) + j][i]
			matrix[(mid_row) + j][i] = back
			back = current
			i += 1
			k -= 1
			j += 1
		
		i = mid_col + 1
		j = 1
		while (i <= e_col and k > 0) :
			current = matrix[e_row - j][i]
			matrix[e_row - j][i] = back
			back = current
			i += 1
			k -= 1
			j += 1
		
		i = e_col - 1
		j = 1
		while (i >= mid_col and k > 0) :
			current = matrix[(mid_row) - j][i]
			matrix[(mid_row) - j][i] = back
			back = current
			i -= 1
			k -= 1
			j += 1
		
		if (s_row + 1 <= e_row - 1 and k > 0) :
			self.rotate_element(matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k)
		
	
	# Count number of diamond element
	def element_size(self, col) :
		counter = 0
		while (col > 0) :
			counter += col
			col -= 1
		
		return counter * 4
	
	def rotate(self, matrix) :
		if (self.rows != self.cols or self.cols % 2 == 0) :
			print("\nNot a valid perfect Odd square matrix", end = "")
			return
		
		size = self.element_size(int((self.cols) / 2)) + 1
		self.rotate_element(matrix, 0, 0, self.rows - 1, self.cols - 1, size)
	
	def show(self, matrix, row, col) :
		i = col
		while (i < (self.cols) - col) :
			print(" ", matrix[row][i] ,end = "")
			i += 1
		
	
	def space(self, size) :
		i = 0
		while (i <= size) :
			print(" ", end = "")
			i += 1
		
	
	def diamond_view(self, matrix) :
		if (self.rows != self.cols or self.cols % 2 == 0) :
			print("\nNot a valid perfect Odd square matrix", end = "")
			return
		
		col = int(self.cols / 2)
		counter = col * 3
		distance = 3
		i = 0
		while (i < self.rows) :
			self.space(counter)
			self.show(matrix, i, col)
			if (i < int(self.rows / 2)) :
				counter -= distance
				col -= 1
			else :
				col += 1
				counter += distance
			
			print("\n", end = "")
			i += 1
		
	

def main() :
	matrix = [
		[1, 2, 3, 4, 5],
		[6, -7, 8, 2, 10],
		[2, 12, 13, 15, 16],
		[17, 2, 19, 20, 21],
		[22, 23, 24, 25, 2]
	]
	obj = MyMatrix(matrix)
	obj.diamond_view(matrix)
	obj.rotate(matrix)
	obj.diamond_view(matrix)


if __name__ == "__main__":
	main()

Output

         3
      -7  8  2
   2  12  13  15  16
      2  19  20
         24
         2
      3  15  16
   -7  8  13  19  20
      2  12  24
         2
# Ruby Program
# Rotate middle diamond element in matrix by anticlockwise
class MyMatrix 
	# Define the accessor and reader of class MyMatrix
    attr_reader :rows, :cols
    attr_accessor :rows, :cols
	def initialize(matrix) 
		# Get the size of matrix
		self.rows = matrix.length
		self.cols = matrix[0].length
	end
	# Rotate diamond element in square matrix anticlockwise
	def rotate_element(matrix, s_row, s_col, e_row, e_col, k) 
		mid_col = s_col + ((e_col - s_col) / 2)
		mid_row = mid_col
		back = matrix[s_row][mid_col]
		current = 0
		i = mid_col - 1
		j = 1
		while (i >= s_col && k > 0) 
			current = matrix[s_row + j][i]
			matrix[s_row + j][i] = back
			back = current
			i -= 1
			k -= 1
			j += 1
		end
		i = s_col + 1
		j = 1
		while (i <= mid_col && k > 0) 
			current = matrix[(mid_row) + j][i]
			matrix[(mid_row) + j][i] = back
			back = current
			i += 1
			k -= 1
			j += 1
		end
		i = mid_col + 1
		j = 1
		while (i <= e_col && k > 0) 
			current = matrix[e_row - j][i]
			matrix[e_row - j][i] = back
			back = current
			i += 1
			k -= 1
			j += 1
		end
		i = e_col - 1
		j = 1
		while (i >= mid_col && k > 0) 
			current = matrix[(mid_row) - j][i]
			matrix[(mid_row) - j][i] = back
			back = current
			i -= 1
			k -= 1
			j += 1
		end
		if (s_row + 1 <= e_row - 1 && k > 0) 
			self.rotate_element(matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k)
		end
	end
	# Count number of diamond element
	def element_size(col) 
		counter = 0
		while (col > 0) 
			counter += col
			col -= 1
		end
		return counter * 4
	end
	def rotate(matrix) 
		if (self.rows != self.cols || self.cols % 2 == 0) 
			print("\nNot a valid perfect Odd square matrix")
			return
		end
		size = self.element_size((self.cols) / 2) + 1
		self.rotate_element(matrix, 0, 0, self.rows - 1, self.cols - 1, size)
	end
	def show(matrix, row, col) 
		i = col
		while (i < (self.cols) - col) 
			print(" ", matrix[row][i] ," ")
			i += 1
		end
	end
	def space(size) 
		i = 0
		while (i <= size) 
			print(" ")
			i += 1
		end
	end
	def diamond_view(matrix) 
		if (self.rows != self.cols || self.cols % 2 == 0) 
			print("\nNot a valid perfect Odd square matrix")
			return
		end
		col = self.cols / 2
		counter = col * 3
		distance = 3
		i = 0
		while (i < self.rows) 
			self.space(counter)
			self.show(matrix, i, col)
			if (i < self.rows / 2) 
				counter -= distance
				col -= 1
			else 
				col += 1
				counter += distance
			end
			print("\n")
			i += 1
		end
	end
end
def main() 
	matrix = [
		[1, 2, 3, 4, 5],
		[6, -7, 8, 2, 10],
		[2, 12, 13, 15, 16],
		[17, 2, 19, 20, 21],
		[22, 23, 24, 25, 2]
	]
	obj = MyMatrix.new(matrix)
	obj.diamond_view(matrix)
	obj.rotate(matrix)
	obj.diamond_view(matrix)
end


main()

Output

        3 
     -7  8  2 
  2  12  13  15  16 
     2  19  20 
        24 
        2 
     3  15  16 
  -7  8  13  19  20 
     2  12  24 
        2 
/*
  Scala Program
  Rotate middle diamond element in matrix by anticlockwise
*/
class MyMatrix(var rows: Int,
		var cols: Int) {

	def this(matrix: Array[Array[Int]]) {
		//Get the size of matrix
		this(matrix.length,matrix(0).length);
	}
	//Rotate diamond element in square matrix anticlockwise
	def rotate_element(matrix: Array[Array[Int]], s_row: Int, s_col: Int, e_row: Int, e_col: Int, k_size: Int): Unit = {
      	var k : Int = k_size;
		val mid_col: Int = s_col + (((e_col - s_col) / 2).toInt);
		val mid_row: Int = mid_col;
		var back: Int = matrix(s_row)(mid_col);
		var current: Int = 0;
		var i: Int = mid_col - 1;
		var j: Int = 1;
		while (i >= s_col && k > 0) {
			current = matrix(s_row + j)(i);
			matrix(s_row + j)(i) = back;
			back = current;
			i -= 1;
			k -= 1;
			j += 1;
		}
		i = s_col + 1;
		j = 1;
		while (i <= mid_col && k > 0) {
			current = matrix((mid_row) + j)(i);
			matrix((mid_row) + j)(i) = back;
			back = current;
			i += 1;
			k -= 1;
			j += 1;
		}
		i = mid_col + 1;
		j = 1;
		while (i <= e_col && k > 0) {
			current = matrix(e_row - j)(i);
			matrix(e_row - j)(i) = back;
			back = current;
			i += 1;
			k -= 1;
			j += 1;
		}
		i = e_col - 1;
		j = 1;
		while (i >= mid_col && k > 0) {
			current = matrix((mid_row) - j)(i);
			matrix((mid_row) - j)(i) = back;
			back = current;
			i -= 1;
			k -= 1;
			j += 1;
		}
		if (s_row + 1 <= e_row - 1 && k > 0) {
			this.rotate_element(matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k);
		}
	}
	//Count number of diamond element
	def element_size(size: Int): Int = {
		var counter: Int = 0;
     	var col: Int = size;
		while (col > 0) {
			counter += col;
			col -= 1;
		}
		return counter * 4;
	}
	def rotate(matrix: Array[Array[Int]]): Unit = {
		if (this.rows != this.cols || this.cols % 2 == 0) {
			print("\nNot a valid perfect Odd square matrix");

			return;
		}
		val size: Int = this.element_size(((this.cols) / 2).toInt) + 1;
		this.rotate_element(matrix, 0, 0, this.rows - 1, this.cols - 1, size);
	}
	def show(matrix: Array[Array[Int]], row: Int, col: Int): Unit = {
		var i: Int = col;
		while (i < (this.cols) - col) {
			print(" " + matrix(row)(i) + " ");
			i += 1;
		}
	}
	def space(size: Int): Unit = {
		var i: Int = 0;
		while (i <= size) {
			print(" ");
			i += 1;
		}
	}
	def diamond_view(matrix: Array[Array[Int]]): Unit = {
		if (this.rows != this.cols || this.cols % 2 == 0) {
			print("\nNot a valid perfect Odd square matrix");

			return;
		}
		var col: Int = (this.cols / 2).toInt;
		var counter: Int = col * 3;
		val distance: Int = 3;
		var i: Int = 0;
		while (i < this.rows) {
			this.space(counter);
			this.show(matrix, i, col);

			if (i < (this.rows / 2).toInt) {
				counter -= distance;
				col -= 1;
			} else {
				col += 1;
				counter += distance;
			}
			print("\n");
			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, 2, 10),
			Array(2, 12, 13, 15, 16),
			Array(17, 2, 19, 20, 21),
			Array(22, 23, 24, 25, 2));
		val obj: MyMatrix = new MyMatrix(matrix);
		obj.diamond_view(matrix);
		obj.rotate(matrix);
		obj.diamond_view(matrix);
	}
}

Output

        3
     -7  8  2
  2  12  13  15  16
     2  19  20
        24
        2
     3  15  16
  -7  8  13  19  20
     2  12  24
        2
/*
  Swift Program
  Rotate middle diamond element in matrix by anticlockwise
*/
class MyMatrix {
	var rows: Int;
	var cols: Int;
	init(_ matrix: [
		[Int]
	]) {
		//Get the size of matrix
		self.rows = matrix.count;
		self.cols = matrix[0].count;
	}
	//Rotate diamond element in square matrix anticlockwise
	func rotate_element(_ matrix: inout [
		[Int]
	], _ s_row: Int, _ s_col: Int, _ e_row: Int, _ e_col: Int, _ k_size: Int) {
      	var k : Int = k_size;
		let mid_col: Int = s_col + ((e_col - s_col) / 2);
		let mid_row: Int = mid_col;
		var back: Int = matrix[s_row][mid_col];
		var current: Int = 0;
		var i: Int = mid_col - 1;
		var j: Int = 1;
		while (i >= s_col && k > 0) {
			current = matrix[s_row + j][i];
			matrix[s_row + j][i] = back;
			back = current;
			i -= 1;
			k -= 1;
			j += 1;
		}
		i = s_col + 1;
		j = 1;
		while (i <= mid_col && k > 0) {
			current = matrix[(mid_row) + j][i];
			matrix[(mid_row) + j][i] = back;
			back = current;
			i += 1;
			k -= 1;
			j += 1;
		}
		i = mid_col + 1;
		j = 1;
		while (i <= e_col && k > 0) {
			current = matrix[e_row - j][i];
			matrix[e_row - j][i] = back;
			back = current;
			i += 1;
			k -= 1;
			j += 1;
		}
		i = e_col - 1;
		j = 1;
		while (i >= mid_col && k > 0) {
			current = matrix[(mid_row) - j][i];
			matrix[(mid_row) - j][i] = back;
			back = current;
			i -= 1;
			k -= 1;
			j += 1;
		}
		if (s_row + 1 <= e_row - 1 && k > 0) {
			self.rotate_element(&matrix, s_row + 1, s_col + 1, e_row - 1, e_col - 1, k);
		}
	}
	//Count number of diamond element
	func element_size(_ size: Int) -> Int {
		var counter: Int = 0;
      	var col: Int = size;
		while (col > 0) {
			counter += col;
			col -= 1;
		}
		return counter * 4;
	}
	func rotate(_ matrix: inout [
		[Int]
	]) {
		if (self.rows != self.cols || self.cols % 2 == 0) {
			print("\nNot a valid perfect Odd square matrix", terminator: "");
			return;
		}
		let size: Int = self.element_size((self.cols) / 2) + 1;
		self.rotate_element(&matrix, 0, 0, self.rows - 1, self.cols - 1, size);
	}
	func show(_ matrix: [
		[Int]
	], _ row: Int, _ col: Int) {
		var i: Int = col;
		while (i < (self.cols) - col) {
			print(matrix[row][i] , terminator: " ");
			i += 1;
		}
	}
	func space(_ size: Int) {
		var i: Int = 0;
		while (i <= size) {
			print( terminator: " ");
			i += 1;
		}
	}
	func diamond_view(_ matrix: [
		[Int]
	]) {
		if (self.rows != self.cols || self.cols % 2 == 0) {
			print("\nNot a valid perfect Odd square matrix", terminator: "");
			return;
		}
		var col: Int = self.cols / 2;
		var counter: Int = col * 3;
		let distance: Int = 3;
		var i: Int = 0;
		while (i < self.rows) {
			self.space(counter);
			self.show(matrix, i, col);
			if (i < self.rows / 2) {
				counter -= distance;
				col -= 1;
			} else {
				col += 1;
				counter += distance;
			}
			print("\n", terminator: "");
			i += 1;
		}
	}
}
func main() {
	var matrix: [
		[Int]
	] = [
		[1, 2, 3, 4, 5],
		[6, -7, 8, 2, 10],
		[2, 12, 13, 15, 16],
		[17, 2, 19, 20, 21],
		[22, 23, 24, 25, 2]
	];
	let obj: MyMatrix = MyMatrix(matrix);
	obj.diamond_view(matrix);
	obj.rotate(&matrix);
	obj.diamond_view(matrix);
}
main();

Output

       3
    -7 8 2
 2 12 13 15 16
    2 19 20
       24
       2
    3 15 16
 -7 8 13 19 20
    2 12 24
       2

Output Explanation

The mentioned Java code correctly implements the above algorithm to rotate the middle diamond elements in the matrix anticlockwise. It calculates the middle column and row of the diamond and traverses the edges while rotating the elements. The rotate function checks for valid matrix dimensions and calculates the number of diamond elements. The output displays the matrix before and after the rotation.

Time Complexity

The time complexity of the mentioned solution is O(N), where N is the number of diamond elements in the matrix. The rotate_element function iterates through each diamond element exactly once and performs constant-time operations (swapping elements). 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