螺旋矩陣
螺旋矩陣就是一個把矩陣打印順序改變的方法,打印的順序在計算機是沒法法改變的,所以只能改變數組存儲的數據。可以先初始化一個全部數據爲0的二維數組,然後開始向右邊走,當右邊的一個位置沒有被訪問過!visit[x][y + 1]並且沒有超過邊界就往右走,這樣的巧妙性在於沒有影響右邊的值,也沒有改變y的值。賦值直接使用a[x][++y] = [需要的值]就行了。第一個值需要先賦值。
#include<bits/stdc++.h>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int main(){
int n,i,j,x,y,r,c,tot,minn=9999;
int *s = new int[10000]{0};
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&s[i]);
sort(s,s+n,cmp);
for(i=1;i<=sqrt(n*1.0);i++)
{
if(n%i==0)
{
if(n/i-i<minn){
minn=n/i-i;
r=i;
}
}
}
c=n/r;//c>r c行r列
int **a;
a = new int*[c+1];
for(int i=0;i<c+1;i++)
{
*(a+i)=new int[r+1];
for(int j=0;j<r+1;j++)
{
*(*(a+i)+j)=0;
}
}
a[0][0]=s[0];
tot=x=y=0;
while(tot < r * c-1)//核心螺旋矩陣部分
{
while(y + 1 < r && ! a[x][y + 1])
a[x][++y] = s[++tot];
while(x + 1 < c && !a[x + 1][y])
a[++x][y] = s[++tot];
while(y - 1 >= 0 && !a[x][y - 1])
a[x][--y] = s[++tot];
while(x - 1 >= 0 && !a[x - 1][y])
a[--x][y] = s[++tot];
}
for(i=0;i<c;i++){
printf("%d",a[i][0]);
for(j=1;j<r;j++){
printf(" %d",a[i][j]);
}
printf("\n");
}
return 0;
}
題目出自pat1050,大概就是這個效果。