最近在 C++ 博客上看到了一段优雅的二维数组赋值代码,学习了一下。
作者为了实现图片中特定效果的二维数组,参考迷宫问题设计了一个优雅的算法,算法的基本思想就是对二维数组按照从外到内的方式赋值,在赋值的过程中加入了对二维数组边界的判断,只需要一层循环就可以实现。整个赋值过程和四冲程发动机工作原理有点类似,循环往复,各种变量之间此消彼长,代码如下:

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;
}


  • E29451d0-a5e8-356d-942c-726a1dd73343-thumb
  • 描述: 循环赋值后的结果
  • 大小: 3.7 KB
评论
发表评论

您还没有登录,请登录后发表评论