PAT B1050 螺旋矩阵 (25point(s))

本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。

输入格式:

输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 10​4​​,相邻数字以空格分隔。

输出格式:

输出螺旋矩阵。每行 n 个数字,共 m 行。相邻数字以 1 个空格分隔,行末不得有多余空格。

输入样例:

12
37 76 20 98 76 42 53 95 60 81 58 93

输出样例:

98 95 93
42 37 81
53 20 76
58 60 76
  • 思路1:按规则将数组存入二维矩阵再输出

step 1: 行和列的获取,行 >= 列,因为sqrt(n) * sqrt(n) = n,不可能行和列都比sqr小,否则乘积必<n; 故行>=sqr,列<=sqr, 可从sqr向下枚举找到第一个可被n整除的数,即为列,向上即为行(求出列后,直接用n / col即可)

step 2: 先将第一个元素存入,然后每走一步提前判断是否合法(越界否?是否已有元素?),若合法走下一步,否则顺时针转90度(用四个循环来控制)

  • code:
#include <bits/stdc++.h>
using namespace std;
int in[11000], ans[11000][11000];
bool T(int x, int y, int c, int r){
	return  ans[y][x] != 0 || x < 1 || x > c || y < 1 || y > r ? false : true;
}
int Getn(int n){
	int sqr = sqrt(1.0 * n);
	while(n % sqr != 0){
		sqr--;
	}
	return sqr;
}
void Print(int r, int c){
	for(int i = 1; i <= r; ++i){
		for(int j = 1; j <= c; ++j){
			if(j == 1) printf("%d", ans[i][j]);
			else printf(" %d", ans[i][j]);
		}
		printf("\n");
	}

}
int main(){
	int n;
	scanf("%d", &n);
	for(int i = 0; i < n; ++i) scanf("%d", &in[i]);
	int col = Getn(n);
	int row = n / col; 
	int x = 1, y = 1, idex = 0;
	sort(in, in+n, greater<int>());
	ans[y][x] = in[idex++];
	while(idex < n){
		while(idex < n && T(x+1, y, col, row)){
			ans[y][++x] = in[idex++]; 
		} 
		while(idex < n && T(x, y+1, col, row)){
			ans[++y][x] = in[idex++]; 
		} 
		while(idex < n && T(x-1, y, col, row)){
			ans[y][--x] = in[idex++]; 
		} 
		while(idex < n && T(x, y-1, col, row)){	
			ans[--y][x] = in[idex++]; 
		} 
	} 
	Print(row, col);
	return 0;
} 
  • 思路2: 优先队列+增量数组+ctl控制
    纯粹是想练练优先队列的写法(用的不多),排序就可以

通过增量数组控制(x, y),随着ctl++,方向变化为:右,下,左,上…不断重复, 为了实现这个不断重复的效果,ctrl % 4;这样就实现了每次“碰壁”,旋转90度的效果。

步骤:将元素压入优先队列,初始 (x,y) = (1, 1);
每次取队首,存入G[x][y]中,若下一步“碰壁”,更新ctl = (ctl + 1) % 4;(旋转90度)直到队空结束,输出二维数组

  • T2 code
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
int G[maxn][maxn];
int X[5] = {0, 1, 0, -1};	//右、下、左、上 
int Y[5] = {1, 0, -1, 0};
bool Judge(int x, int y, int r, int c){
	return  G[x][y] != 0 || x < 1 || x > r || y < 1 || y > c ? true : false;
}
int main(){
	int n;
	scanf("%d", &n);
	priority_queue<int, vector<int>, less<int> > pq;
	for(int i = 0; i < n; ++i){
		int tmp;
		scanf("%d", &tmp);
		pq.push(tmp);
	}
	int col = sqrt(1.0 * n);
	while(n % col != 0){	//Wrong 1:
		col--;
	}
	int row = n / col, x = 1, y = 1, ctl = 0;
	while(!pq.empty()){
		G[x][y] = pq.top();
		pq.pop();
		if(Judge(x + X[ctl], y + Y[ctl], row, col)){
			ctl = (ctl + 1) % 4; 
		} 
		x = x + X[ctl];
		y = y + Y[ctl];  				
	}
	for(int i = 1; i <= row; ++i){
		for(int j = 1; j <= col; ++j){
			printf("%d", G[i][j]);
			if(j < col) printf(" ");
		}
		printf("\n");
	}
	return 0;
} 
发布了271 篇原创文章 · 获赞 5 · 访问量 6522

猜你喜欢

转载自blog.csdn.net/qq_42347617/article/details/104166101