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;}
新闻热点
疑难解答