您的位置:首页 > 其它

Rotating clockwise inward matrix

2015-06-28 21:23 344 查看
Problem:

Write a program to: 1) wait for the user to input a positive integer N, and 2) output a NxN matrix on the screen with numbers 1 to N, rotating clockwise inward. For example, if N = 4, then the output should be:

1 2 3 4

12 13 14 5

11 16 15 6

10 9 8 7

Answer:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
int N;
cin >> N;
int m = N;
int c = 0;
vector<vector<int> > a(N, vector<int>(N, 0));
int i = 1;
int x = 0;
int y = 0;
int count = 0;
while (i <= N * N) {
a[x][y] = i;
++i;
++count;
if (x == c && y < m-1) {
++y;
}
else if (y == m -1 && x < m-1) {
++x;
}
else if (x == m - 1 && y > c) {
--y;
}
else if (y == c && x > c) {
--x;
}
if (count == (m-c)*4 - 4) {
++c;
--m;
x = c;
y = c;
count = 0;
}
}

for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
cout << a[j][k] << " ";
}
cout << endl;
}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: