随笔 - 89  文章 - 118  trackbacks - 0
<2008年3月>
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345

留言簿(16)

随笔分类(56)

随笔档案(89)

文章分类

推荐博客

搜索

  •  

最新随笔

最新评论

阅读排行榜

曾经遇到一个为二维数组循环赋值的问题,即赋值后的二维数组为如下情形:



当时在网上找了一下答案,基本上都是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 胡满超 阅读(4794) 评论(2)  编辑 收藏 引用

FeedBack:
# re: 为二维数组循环赋值 2008-03-04 14:39 Enoch
沙发!
不错,这个与循环相比,时空性怎样啊!
分析时空性,我想这篇大作应该不只是
“如下代码要优雅一些”

顶!  回复  更多评论
  
# re: 为二维数组循环赋值 2008-03-04 16:29 raof01
//时空性能还行,比楼主的代码难看多啦~~
template <size_t N1, size_t N2>
void Convert(int (&array)[N1][N2])
{
int all = N1 * N2;
int i = 0;
int j = -1;
int direction = 0;
int val = 0;
while(val < all)
{
if (0 == direction)
{
++j;
if (j < N2 && -1 == array[i][j])
{
array[i][j] = val;
}
else
{
direction = 1;
--j;
}
}
if (1 == direction)
{
++i;
if (i < N1 && -1 == array[i][j])
{
array[i][j] = val;
}
else
{
direction = 2;
--i;
}
}
if (2 == direction)
{
--j;
if (j >= 0 && -1 == array[i][j])
{
array[i][j] = val;
}
else
{
direction = 3;
++j;
}
}
if (3 == direction)
{
--i;
if (i >= 0 && -1 == array[i][j])
{
array[i][j] = val;
}
else
{
direction = 0;
++i;
--val;
}
}
++val;
}
}  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理