Created
February 28, 2018 09:33
-
-
Save ArtyomLazyan/4f3afee7d3e49e9f3e4866b7ab94b22c to your computer and use it in GitHub Desktop.
SpiraPrint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
const int N = 5; | |
int count = 1; | |
void spiralPrint(int end_row, int end_col, int arr[N][N]) | |
{ | |
int start_row = 0, start_col = 0; | |
while (start_row < end_row && start_col < end_col) | |
{ | |
/* Print the first row from the remaining rows */ | |
for (int i = start_col; i < end_col; ++i) | |
{ | |
if (count == 5) | |
count = 1; | |
arr[start_row][i] = count; | |
count++; | |
} | |
start_row++; | |
/* Print the last column from the remaining columns */ | |
for (int i = start_row; i < end_row; ++i) | |
{ | |
if (count == 5) | |
count = 1; | |
arr[i][end_col - 1] = count; | |
count++; | |
} | |
end_col--; | |
/* Print the last row from the remaining rows */ | |
if (start_row < end_row) | |
{ | |
for (int i = end_col - 1; i >= start_col; --i) | |
{ | |
if (count == 5) | |
count = 1; | |
arr[end_row - 1][i] = count; | |
count++; | |
} | |
end_row--; | |
} | |
/* Print the first column from the remaining columns */ | |
if (start_col < end_col) | |
{ | |
for (int i = end_row - 1; i >= start_row; --i) | |
{ | |
if (count == 5) | |
count = 1; | |
arr[i][start_col] = count; | |
count++; | |
} | |
start_col++; | |
} | |
} | |
arr[N / 2][N / 2] = 9; | |
for (int i = 0; i < N; i++) | |
{ | |
for (int j = 0; j < N; j++) | |
{ | |
std::cout << arr[i][j] << " "; | |
} | |
std::cout << std::endl; | |
} | |
} | |
/* Driver program to test above functions */ | |
int main() | |
{ | |
int arr[N][N] = { | |
{1, 2, 3, 4, 5}, | |
{4, 5, 6, 5, 8}, | |
{7, 8, 9, 6, 7}, | |
{7, 8, 9, 6, 6}, | |
{7, 8, 9, 6, 8}, | |
}; | |
spiralPrint(N, N, arr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment