Skip to main content

Anticlockwise spiral view of diamond matrix elements in c

Anticlockwise spiral view of matrix

C program for Anticlockwise spiral view of diamond matrix elements. Here mentioned other language solution.

/*
  C Program 
+ Anticlockwise spiral view of diamond element in matrix
*/
#include<stdio.h>

#define ROW 5
#define COL 5
// Method which is displaying the Anticlockwise spiral 
// Of matrix in diamond(mid) element
void spiral_view(int matrix[ROW][COL], 
    int s_row, int s_col, int e_row, int e_col, int k) {
	//Find the middle column
	int mid_col = s_col + ((e_col - s_col) / 2);
	// Get middle row (valid for odd square matrix)
	int mid_row = mid_col;
	// Matrix are divided into 4 section
	// Starting of middle row and column in form of top
	// Top to Left-bottom
	for (int i = mid_col, j = 0; 
         i > s_col && k > 0; i--, k--, j++) {
		printf("%4d", matrix[s_row + j][i]);
	}
	// Middle left to middle right bottom
	for (int i = s_col, j = 0; 
         i <= mid_col && k > 0; i++, k--, j++) {
		printf("%4d", matrix[(mid_row) + j][i]);
	}
	// Middle bottom to middle right side 
	for (int i = mid_col + 1, j = 1; 
         i <= e_col && k > 0; i++, k--, j++) {
		printf("%4d", matrix[(e_row) - j][i]);
	}
	// Middle right side to  top middle 
	for (int i = e_col - 1, j = 1; 
         i > mid_col && k > 0; i--, k--, j++) {
		printf("%4d", matrix[(mid_row) - j][i]);
	}
	if (s_row + 1 <= e_row - 1 && k > 0) {
		//Recursive call
		spiral_view(matrix, s_row + 1, 
                    s_col + 1, e_row - 1, e_col - 1, k);
	}
}
void diamond_spiral(int matrix[ROW][COL]) {
	// Check whether the given matrix is a valid odd shape or not
	if (ROW != COL || COL % 2 == 0) {
		// When Yes not a valid size
		printf("\nNot a valid perfect Odd square matrix");
		return;
	}
	// (ROW*COL)-((COL+1)/2)*4 are provide the value of 
    // number of diamond element
	spiral_view(matrix, 0, 0, ROW - 1, COL - 1, 
                (ROW * COL) - ((COL + 1) / 2) * 4);
}
int main() {
    // Matrix element
    int matrix[ROW][COL] ={
      {1,  2,  3,  4,  5},
      {6,  7,  8,  9,  10},
      {11, 12, -1, 15,  16},
      {17, 18, 19, 20,  21},
      {22, 23, 24, 25,  26}
    }; 
	diamond_spiral(matrix);
	return 0;
}

Output

   3   7  11  18  24  20  16   9   8  12  19  15  -1




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