#include <stdio.h>
#include <exception>
void MyPrintMatrix(int* matrix, int row, int column) {
if(matrix == NULL || row == 0 || column == 0)
throw std::exception();
//initial sign matrix to note which number has been print
int* sign = new int[row*column];
for(int i=0; i<row; ++i) {
for(int j=0; j<column; ++j)
sign[i*column+j] = 0;
}
int i=0, j=0, count=row*column;
while(1 != count) {
//move right
while(j < column-1 && !sign[i*column+j+1]) {
sign[i*column+j] = 1;--count;
printf("%d/", matrix[i*column+j]);
++j;
}
//move down
while(i<row-1 && !sign[(i+1)*column+j]) {
sign[i*column+j] = 1;--count;
printf("%d/", matrix[i*column+j]);
++i;
}
//move left
while(i>0 && !sign[(i-1)*column+j]) {
sign[i*column+j] = 1;--count;
printf("%d/", matrix[i*column+j]);
--i;
}
//move up
while(j>0 && !sign[i*column+j-1]) {
sign[i*column+j] = 1;--count;
printf("%d/", matrix[i*column+j]);
--j;
}
}
//print last number
printf("%d\n", matrix[i*column+j]);
delete []sign;
}
void PrintOriginalMatrix(int* matrix, int row, int column) {
for(int i=0; i<row; ++i) {
for(int j=0; j<column; ++j) {
printf("%d ", matrix[i*column+j]);
}
printf("\n");
}
}
void Test(const char* testName, int* matrix, int row, int column) {
if(testName != NULL)
printf("%s begins:\n", testName);
PrintOriginalMatrix(matrix, row, column);
MyPrintMatrix(matrix, row, column);
}
//4*4
void Test1() {
int matrix[][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
Test("Test1", (int*)matrix, 4, 4);
}
//1*5
void Test2() {
int matrix[][5] = {{1,2,3,4,5}};
Test("Test2", (int*)matrix, 1, 5);
}
//5*1
void Test3() {
int matrix[][1] = {{1},{2},{3},{4},{5}};
Test("Test3", (int*)matrix, 5, 1);
}
//2*2
void Test4() {
int matrix[][2] = {{1,2},{3,4}};
Test("Test4", (int*)matrix, 2, 2);
}
//5*3
void Test5() {
int matrix[][3] = {{1,2,3},{2,3,4},{3,4,5},{4,5,6},{5,6,7}};
Test("Test5", (int*)matrix, 5, 3);
}
int main(int argc, char* argv[]) {
Test1();
Test2();
Test3();
Test4();
Test5();
return 0;
}