1105. Spiral Matrix (25) -- 模拟
2017-02-14 19:18
417 查看
题目地址
https://www.patest.cn/contests/pat-a-practise/1105ac代码
思路是:外围转一圈的函数封装起来,然后遍历填充,注意判断是否完成了#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <string> #include <vector> #include <queue> #include <algorithm> #include <sstream> #include <list> #include <stack> #include <map> #include <set> #include <iterator> #include <unordered_map> using namespace std; #define INF 0x7fffffff typedef long long int LL; const int N = 404; int n; vector<int> v; bool cmp(int a, int b) { return a > b; } int r; int c; vector<vector<int>> ans; void func(int stai,int staj,int endi,int endj,int index) { if(stai == endi) // 只有一行 { for(int j=staj;j<=endj;j++){ ans[stai][j] = v[index++]; if(index > n) break; } return; } if(staj == endj) // 只有一列 { for(int i=stai;i<=endi;i++){ ans[i][staj] = v[index++]; if(index > n) break; } return; } for(int j=staj;j<=endj;j++){ ans[stai][j] = v[index++]; if(index > n) break; } for(int i = stai + 1; i <= endi;i++) { ans[i][endj] = v[index++]; if(index > n) break; } for(int j = endj - 1; j >= staj ; j--) { ans[endi][j] = v[index++]; if(index > n) break; } for(int i= endi - 1;i>=stai+1;i--) { ans[i][staj] = v[index++]; if(index > n) break; } } int main() { //freopen("in.txt", "r" , stdin); while(scanf("%d", &n) != EOF) { for(int i=0;i<n;i++) { int tmp; scanf("%d", &tmp); v.push_back(tmp); } sort(v.begin(), v.end(), cmp); r = n; c = 1; int cha = r - c; for(int i=1;i<=n;i++) { for(int j=1;j<=i;j++) { if(i * j == n) { if(i - j < cha) { r = i; c = j; cha = i - j; } } } } vector<vector<int>> ansT(r, vector<int>(c)); ans = ansT; int stai = 0; int endi = r - 1; int staj = 0; int endj = c - 1; int index = 0; while(index < n) { int cnt = 2 * (endj - staj + 1) + 2 * (endi - stai + 1 - 2); func(stai, staj, endi, endj, index); index += cnt; stai ++; staj ++; endi --; endj --; } for(int i=0;i<r;i++) { cout << ans[i][0]; for(int j=1;j<c;j++) { cout << " " << ans[i][j]; } cout << endl; } } return 0; }
相关文章推荐
- 1105. Spiral Matrix (25) 模拟
- 1105. Spiral Matrix (25) 排序、模拟
- PAT 1105. Spiral Matrix (25) 螺旋矩阵,二维数组的一维应用及边界模拟
- PAT - 甲级 - 1105. Spiral Matrix (25)(模拟)
- PAT甲题题解-1105. Spiral Matrix (25)-(模拟顺时针矩阵)
- 1105. Spiral Matrix (25)【模拟】——PAT (Advanced Level) Practise
- 1105. Spiral Matrix (25)
- 1105. Spiral Matrix (25)解题报告
- PAT甲级 1105. Spiral Matrix (25)
- 1105. Spiral Matrix(25)
- PTA甲 1105. Spiral Matrix (25)
- 1105. Spiral Matrix (25)[数组处理]
- pat 1105. Spiral Matrix (25)
- 1105. Spiral Matrix (25)
- 【PAT】【Advanced Level】1105. Spiral Matrix (25)
- PAT (Advanced Level) Practise 1105. Spiral Matrix (25) 蛇形填数
- PAT (Advanced Level) 1105. Spiral Matrix (25)
- PAT (Advanced Level) Practise 1105 Spiral Matrix (25)
- 【PAT】1105. Spiral Matrix (25)
- 1105. Spiral Matrix (25)