面试题-螺旋队列

来源:互联网 发布:企业审计软件 编辑:程序博客网 时间:2024/04/30 17:26

21     22............

20     7     8     9     10

19     6     1     2     11

18     5     4     3     12

17    16   15   14    13

设1的坐标是(0,0),x方向向右为正,y方向向下为正,例如,7的坐标为(-1,-1),2的坐标为(1,0)。编程实现输入任意一点坐标(x,y),输出所对应的数字!

思路: 博客http://blog.csdn.net/yhmhappy2006/article/details/2934435

c语言:

// luoxuan.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include<stdio.h>#define max(a,b) (a < b ? b : a)#define abs(a) (a > 0 ? a : -(a))int SpiralQueue (int x, int y){int circle = max(abs(x),abs(y));int max_num = (2*circle+1) * (2*circle +1);if(y == -circle){//topreturn max_num + (x+y);}else if( x == -circle){//leftreturn max_num + (3 * x - y);}else if( y == circle){//bottomreturn max_num + (-x - 5 * y);}else{//rightreturn max_num + (-7 * x + y);}}int main(int argc, char* argv[]){int x,y;while(scanf("%d%d", &x, &y) == 2)printf("%d\n",SpiralQueue(x,y));return 0;}

python:

def SpiralQueue(x,y):    circle = max(abs(x),abs(y))    max_num = pow((2 * circle + 1),2)    #top    if( y == -circle):        return max_num + (y + x)    #left    elif ( x == - circle):        return max_num + 3 * x - y    #bottom    elif( y == circle):        return max_num -5 * y - x    #right    else:        return max_num - 7 * x  + yif __name__ == '__main__':    while True:        x = input("input x:")        y = input("input y:")        print SpiralQueue(x,y)


原创粉丝点击