坐标转换问题
题目如下:给一个表如下,
21 ,22 ,33 ,32 ,44
20 ,7 ,8, 9 ,10
19 ,6, 1, 2,11
18, 5, 4, 3,12
17,16, 15,14,14
设1点的坐标是(0,0),x方向向右为正,y方向向下为正。例如,7的坐标是(-1,-1),2的坐标是(1,0),3的坐标是(1,1)。编程实现输入任意一点坐标(x,y),输出对应的数字。
并且怎样实现效率较高?
[解决办法]
楼主先看看螺旋矩阵的生成,
然后自然就知道下标的值了 ~
/* The following can be compiled and executed in
* visual C++ 6.0 sp6 */
#include "stdio.h "
#define MAX_AM 100
int helixMatrix[MAX_AM][MAX_AM]; // global variable
/*
*(mt_x,mt_y): coordinate of the 1st element
* start:the value of 1st element
* n: the size of the helixMatrix
*/
void SethelixMatrix(int mt_x, int mt_y, int start, int n)
{
int i, j;
if (n <= 0) //the qualification of end for the recursion
return;
if (n == 1)
{ //the extreme size of helixMatrix : 1
helixMatrix[mt_x][mt_y] = start;
return;
}
for (i = mt_x; i < mt_x + n-1; i++) //the top of the matrix
{
helixMatrix[mt_y][i] = start++;
}
for (j = mt_y; j < mt_y + n-1; j++) // the right of it
{
helixMatrix[j][mt_x+n-1] = start++;
}
for (i = mt_x+n-1; i > mt_x; i--) //the bottom of it
{
helixMatrix[mt_y+n-1][i] = start++;
}
for (j = mt_y+n-1; j > mt_y; j--) //the left of it
{
helixMatrix[j][mt_x] = start++;
}
SethelixMatrix(mt_x+1, mt_y+1, start, n-2); // the recursion
}
void main()
{
int i, j;
int n;
printf( " Input the size you want ");
printf( "\n\t ");
scanf( "%d ", &n);
SethelixMatrix(0, 0, 1, n);
//print the helixMatrix
for(i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf( "%4d ", helixMatrix[i][j]);
printf( "\n ");
}
}
//螺旋matrix
[解决办法]
另外的一个笨办法,
不考虑数组的规律,
搜索:
int i, j, num=??, flag=0;
int arr[5][5]={...};
for(i=0; i <5&&!flag; i++)
for(j=0; j <5; j++)if(num == arr[i][j]){flag = 1; break;}
printf( "pos:(%d, %d)\n ", i-2, j-2);