Spiral traversal of matrix in c++

C++ program for Spiral traversal of matrix. Here problem description and explanation.

// Include header file
#include <iostream>
#include <vector>
using namespace std;
// C++ program
// Spiral form of 2d array
class SpiralView
{
	public: void spiral(vector < vector < int >> data, 
                        int startRow, int startCol, 
                        int endRow, int endCol, int element)
	{
		// Left to right
		for (int i = startCol; 
             i <= endCol && element > 0; ++i)
		{
			element--;
			cout << "  " << data[startRow][i];
		}
		// Top to down
		for (int i = startRow + 1; 
             i <= endRow && element > 0; ++i)
		{
			element--;
			cout << "  " << data[i][endCol];
		}
		// Bottom right to bottom-left
		for (int i = endCol - 1; 
             i >= startCol && element > 0; --i)
		{
			element--;
			cout << "  " << data[endRow][i];
		}
		// Bottom left to top
		for (int i = endRow - 1; 
             i > startRow && element > 0; --i)
		{
			element--;
			cout << "  " << data[i][startRow];
		}
		if (startRow + 1 <= endRow - 1 && element > 0)
		{
			// Recursive call
			this->spiral(data, startRow + 1, 
                         startCol + 1, endRow - 1, 
                         endCol - 1, element);
		}
	}
};
int main()
{
	SpiralView *task = new SpiralView();
	// 2d matrix
	vector < vector < int >> matrix
	{
          {1 ,  2 ,  3 ,  4 ,  5 ,  6} , 
          {22 , 23 , 24 , 25 , 26 , 7} , 
          {21 , 36 , 37 , 38 , 27 , 8} , 
          {20 , 35 , 42 , 39 , 28 , 9} , 
          {19 , 34 , 41 , 40 , 29 , 10} , 
          {18 , 33 , 32 , 31 , 30 , 11} , 
          {17 , 16 , 15 , 14 , 13 , 12}  
    }; 
	int row = matrix.size();
	int col = matrix[0].size();
	// Get the number of element
	int element = row *col;
	task->spiral(matrix, 0, 0, row - 1, col - 1, element);
	return 0;
}

Output

  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42


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







© 2021, kalkicode.com, All rights reserved