【发布时间】:2016-10-04 04:49:44
【问题描述】:
对于与上面给出的类似填充的 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 )
}
【问题讨论】:
-
首先,螺旋矩阵的定义是什么?其次,您是如何尝试使用此代码解决问题的?您到底在努力解决什么问题?
-
提示:函数原型应该是
int getnum(int n, int r, int c)。该函数不需要矩阵的副本。事实上,这主要是一道数学题。所以把键盘放在一边,拿起铅笔和纸。 -
“在 5*5 矩阵中找到 [R, C]” -
int mat[4][4]- 你注意到什么了吗?