首页 > 学院 > 开发设计 > 正文

Spiral Matrix II

2019-11-14 09:17:41
字体:
来源:转载
供稿:网友

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,Given n = 3,

You should return the following matrix:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

vector<vector<int> > fun(int n){	vector<vector<int> > result(n, vector<int>(n));	int left = 0;	int right = n-1;	int top = 0;	int bottom = n-1;	int count = 0;	int total = n*n;	while (count < total)	{		for (int i = left; i <= right && count < total; i++)		{			count++;			result[top][i] = count;		}		top++;		for (int i = top; i <= bottom && count < total; i++)		{			count++;			result[i][right] = count;		}		right--;		for (int i = right; i >= left && count < total; i--)		{			count++;			result[bottom][i] = count;		}		bottom--;		for (int i = bottom; i >= top && count < total; i--)		{			count++;			result[i][left] = count;		}		left++;	}	return result;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表