P2239 [NOIP2014 普及组] 螺旋矩阵 50分
//O(n^2)复杂度,能算n<=10000的
#include <bits/stdc++.h>
using namespace std;
//row当前行, column当前列, left:左边界,righ:右边界,top:上边界,bottom:下边界
int n, x, y, ans, row=1, column=0, lef, righ, top, bottom;
int main()
{
scanf("%d %d %d", &n, &x, &y);
lef=1; //左边界
righ=n; //右边界
top=2; //上边界
bottom=n; //下边界
while(1){
//从左向右走
while(column<righ){
column++;
ans++;
if(row==x && column==y){
printf("%d", ans);
return 0;
}
}
righ--;
//从上向下走
while(row<bottom){
row++;
ans++;
if(row==x && column==y){
printf("%d", ans);
return 0;
}
}
bottom--;
//从右向左走
while(column>lef){
column--;
ans++;
if(row==x && column==y){
printf("%d", ans);
return 0;
}
}
lef++;
//从下向上走
while(row>top){
row--;
ans++;
if(row==x && column==y){
printf("%d", ans);
return 0;
}
}
top++;
}
return 0;
}
P2239 [NOIP2014 普及组] 螺旋矩阵 递归满分
#include <bits/stdc++.h>
using namespace std;
int n, x, y, ans;
int asd(int n, int row, int column)
{
if(row==1){ //第1行
return column;
}
else if(column==n){ //第n列
return n+row-1;
}
else if(row==n){ //第n行
return 3*n-column-1; //n + n-1 + n-1 - column + 1;
}
else if(column==1){ //第1列
return 4*n-row-2; //n + n-1 + n-1 + n-1 - row +1;
}
else{
return asd(n-2, row-1, column-1)+4*n-4;
}
}
int main()
{
scanf("%d %d %d", &n, &x, &y);
printf("%d", asd(n, x, y));
return 0;
}