曾經(jīng)遇到一個(gè)為二維數(shù)組循環(huán)賦值的問題,即賦值后的二維數(shù)組為如下情形:

當(dāng)時(shí)在網(wǎng)上找了一下答案,基本上都是1層大循環(huán)套4層小循環(huán)還實(shí)現(xiàn)的,感覺不夠優(yōu)雅。最近翻了一下數(shù)據(jù)結(jié)構(gòu)的書,看到迷宮問題受到了一點(diǎn)啟發(fā),感覺同樣是實(shí)現(xiàn)這個(gè)功能,如下代碼要優(yōu)雅一些:
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 ------> 右->下->左->上 循環(huán)
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) // 已經(jīng)有值
{
i--;
nOffset++;
continue;
}
curPos = tempPos;
mat[curPos.nRow][curPos.nCol] = i+1;
}
printMat(mat);
return 0;
}
printMat函數(shù)這些就不提供了,它的功能是打印出這個(gè)數(shù)組。我上傳了一下工程,有興趣的朋友點(diǎn)此下載。
posted on 2008-03-04 10:30
胡滿超 閱讀(4832)
評(píng)論(2) 編輯 收藏 引用