对于一个类似于上面给出的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 )
}
发布于 2017-05-23 13:00:37
我们将在这里使用递归。如果要搜索的元素不是NxN
螺旋矩阵的边界元素,那么我们可以删除边界,检查现在形成的(N-2)x(N-2)
螺旋矩阵中的元素。下面的代码使用此逻辑。(请注意,R
和C
使用基于1的索引)
import java.util.*;
class SpiralElement{
static int getElement(int N, int R, int C){
if(R != 1 && C != 1 && R != N && C != N)return getElement(N-2, R-1, C-1);
else{
if(R == 1)return N*N+1-C;
else if(C == 1)return (N*N) - (N)-(N-1)-(N-2) - (N-R);
else if(R == N)return (N*N) - (N) - (N-1) - (N-2) + (C-1);
else return (N*N) - (N) - (R-2);
}
}
static void main(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter N, R, C");
int N = sc.nextInt();
int R = sc.nextInt();
int C = sc.nextInt();
if(N%2 == 0){
R = N-R+1; // mirroring the position as highest element(N*N) is now the bottom-right element and not top-left
C = N-C+1;
}
System.out.println(getElement(N,R,C));
}
}
https://stackoverflow.com/questions/39844357
复制相似问题