エレガントな2 D配列ループ割り当て
最近C++ブログで優雅な2次元配列付与コードを見て、勉強しました.著者らは,画像中の特定の効果の2次元配列を実現するために,迷宮問題を参考に優雅なアルゴリズムを設計し,アルゴリズムの基本思想は2次元配列に対して外から内への方式で値を付与し,値を付与する過程で2次元配列の境界に対する判断を加え,1層のサイクルで実現できることである.全体の付与過程は4ストロークエンジンの動作原理と少し似ていて、循環往復して、各種変数の間でこの消彼長、コードは以下の通りです.
const int ROW__ = 10;
const int COL__ = 10;
int mat[ROW__][COL__];
struct Position
{
int nRow;
int nCol;
};
int main(int argc, char* argv[])
{
Position offset[4];
// , ,
offset[0].nRow = 0;
offset[0].nCol = 1;
// , ,
offset[1].nRow = 1;
offset[1].nCol = 0;
// , ,
offset[2].nRow = 0;
offset[2].nCol = -1;
// , ,
offset[3].nRow = -1;
offset[3].nCol = 0;
Position curPos;
curPos.nRow = 0;
curPos.nCol = 0;
mat[0][0] = 1;
int nOffset = 0;
Position tempPos;
for (int i = 1; i < ROW__*COL__; i++)
{
// nOffset % 4 ------> -> -> ->
tempPos.nRow = curPos.nRow + offset[nOffset % 4].nRow;
tempPos.nCol = curPos.nCol + offset[nOffset % 4].nCol;
if (tempPos.nRow >= ROW__ || tempPos.nRow < 0
|| tempPos.nCol >= COL__ || tempPos.nCol < 0 //
|| mat[tempPos.nRow][tempPos.nCol] > 0) //
{
i--;
nOffset++;
continue;
}
curPos = tempPos;
mat[curPos.nRow][curPos.nCol] = i + 1;
}
return 0;
}