Regular array Printing
[Beijing zhizhen pen exam] print the following 4*4 arrays, require N * N arrays?
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
[Idea ]:
1. Discovery rules. As shown in, careful discovery is regular. First, steps 1st, 2, 3, and 4. We found steps 5th, 6, and 7... Steps 1, 2, 3, and 4 are the same, but the boundary value is different.
2. Consider Implementation. The implementation problem is to define a two-dimensional array first, and the element of the array is 0. Then the operation is to fill in the value. The boundary value is separated layer by layer. We can easily see that the number of cycles is exactly n/2. If N is an odd number, the last number must be processed separately.
[Algorithm Implementation ]:
// Design [idea: separated layer by layer.]
[Cpp]
Void designArray (int nArray [] [g_nCnt], int nSize)
{
Int nBase = 1;
For (int I = 0; I <g_nCnt/2; I ++)
{
For (int j = I; j <g_nCnt-i; j ++)
{
NArray [I] [j] = nBase ++;
}
For (int j = I + 1; j <g_nCnt-i; j ++)
{
NArray [j] [g_nCnt-i-1] = nBase ++;
}
For (int j = g_nCnt-i-2; j> = I; j --)
{
NArray [g_nCnt-i-1] [j] = nBase ++;
}
For (int j = g_nCnt-i-2; j> I; j --)
{
NArray [j] [I] = nBase ++;
}
If (nSize % 2 = 1)
{
NArray [nSize/2] [nSize/2] = nBase;
}
} // End for I
}
// PrintArray
Void printArray (int nArray [] [g_nCnt], int nSize)
{
Static int s_nCnt = 0;
Cout <"-------------------- DESIGN" <++ s_nCnt;
Cout <"----------------------" <endl;
For (int I = 0; I <nSize; I ++)
{
For (int j = 0; j <nSize; j ++)
{
Cout <nArray [I] [j] <"\ t ";
} // End for j
Cout <endl;
} // End for I
Cout <"-------------------- \ DESIGN" <s_nCnt;
Cout <"----------------------" <endl;
Cout <endl;
}
Void designArray_t (int nArray [] [g_nCnt], int nSize)
{
Int nBase = 1;
For (int I = 0; I <g_nCnt/2; I ++)
{
For (int j = I; j <g_nCnt-i; j ++)
{
NArray [j] [I] = nBase ++;
}
For (int j = I + 1; j <g_nCnt-i; j ++)
{
NArray [g_nCnt-i-1] [j] = nBase ++;
}
For (int j = g_nCnt-i-2; j> = I; j --)
{
NArray [j] [g_nCnt-i-1] = nBase ++;
}
For (int j = g_nCnt-i-2; j> I; j --)
{
NArray [I] [j] = nBase ++;
}
If (nSize % 2 = 1)
{
NArray [nSize/2] [nSize/2] = nBase; // N is an odd number, processing of the last element.
}
} // End for I
}
[Running result]: