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:
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; }
相关文章推荐
- [leetcode] Jump Game
- gradle运行java main
- 玩转oracle学习第七天
- Java CountDownLatch Example(转)
- 无IDE时编译和运行Java
- 《Java程序设计》第16周周五:数据库连接与随机数的使用
- springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)
- Objective-C 快速入门--基础(三)
- 进程互斥(二)Dekker算法
- 玩转oracle学习第六天
- gcc vim c操作命令
- spring set注入
- [STL]C++中placement new操作符(经典)
- 剑指Offer--面试题29:数组中出现超过一半的数字
- [每日刷题(2015/6/27)]在一个分布式银行系统中,你如何测试一台ATM机?
- >输入子系统层次结构
- 文章标题
- 玩转oracle学习第五天
- How to use CyclicBarrier in Java - Concurrency Tutorail(转)
- 莫名其妙的Parse error: syntax error, unexpected $end 分类: php相关 2008-12-17 20:25 7086人阅读 评论(3) 收藏 举报 phpg