对于与上面给出的类似填充的 N*N 螺旋矩阵,找到存在于 [R,C] 位置的元素,其中 R=行数,C=列数。
请记住,我仍然是初学者,所以请不要太提前。
我对螺旋矩阵感到困惑,这也可以,但它是为常规矩阵设计的,鉴于它是螺旋矩阵,我想了解最佳解决方案。谢谢你。
#include<stdio.h>
/* Searches the element x in mat[][]. If the element is found,
then prints its position and returns true, otherwise prints
"not found" and returns false */
int search(int mat[4][4], int n, int x)
{
int i = 0, j = n-1; //set indexes for top right element
while ( i < n && j >= 0 )
{
if ( mat[i][j] == x )
{
printf("\n Found at %d, %d", i, j);
return 1;
}
if ( mat[i][j] > x )
j--;
else // if mat[i][j] < x
i++;
}
printf("\n Element not found");
return 0; // if ( i==n || j== -1 )
}