作者:胡满超 来源:C++博客   酷勤网收集 2008-04-18

摘要
  曾经遇到一个为二维数组循环赋值的问题,当时在网上找了一下答案,基本上都是1层大循环套4层小循环还实现的,感觉不够优雅。最近翻了一下数据结构的书,看到迷宫问题受到了一点启发,感觉同样是实现这个功能,如下代码要优雅一些
曾经遇到一个为二维数组循环赋值的问题,即赋值后的二维数组为如下情形:



当时在网上找了一下答案,基本上都是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函数这些就不提供了,它的功能是打印出这个数组。我上传了一下工程,有兴趣的朋友点此下载

来自:http://www.cppblog.com/humanchao/archive/2008/03/04/43655.html

分类: 算法艺术 设计模式



关于酷勤 | 联系方式 | 免责声明 | 友情链接