Rotating clockwise inward matrix

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:

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int N;
 9     cin >> N;
10     int m = N;
11     int c = 0;
12     vector<vector<int> > a(N, vector<int>(N, 0));
13     int i = 1;
14     int x = 0;
15     int y = 0;
16     int count = 0;
17     while (i <= N * N) {
18         a[x][y] = i;
19         ++i;
20         ++count;
21         if (x == c && y < m-1) {
22             ++y;
23         }
24         else if (y == m -1 && x < m-1) {
25             ++x;
26         }
27         else if (x == m - 1 && y > c) {
28             --y;
29         }
30         else if (y == c && x > c) {
31             --x;
32         }
33         if (count == (m-c)*4 - 4) {
34             ++c;
35             --m;
36             x = c;
37             y = c;
38             count = 0;
39         }
40     }
41 
42     
43     for (int j = 0; j < N; ++j) {
44         for (int k = 0; k < N; ++k) {
45             cout << a[j][k] << " ";
46         }
47         cout << endl;
48     }
49     
50     return 0;            
51         
52 }

 

转载于:https://www.cnblogs.com/unistation/p/4606129.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值