曾經遇到一個為二維數組循環賦值的問題,即賦值后的二維數組為如下情形:

當時在網上找了一下答案,基本上都是1層大循環套4層小循環還實現的,感覺不夠優雅。最近翻了一下數據結構的書,看到迷宮問題受到了一點啟發,感覺同樣是實現這個功能,如下代碼要優雅一些:
const int ROW__ = 10;
const int COL__ = 10;
int mat[ROW__][COL__];
struct Position
{
int nRow;
int nCol;
};
void printMat(int mat[ROW__][COL__]);
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;
}
printMat(mat);
return 0;
}
printMat函數這些就不提供了,它的功能是打印出這個數組。我上傳了一下工程,有興趣的朋友點此下載。
posted on 2008-03-04 10:30
胡滿超 閱讀(4823)
評論(2) 編輯 收藏 引用