【问题标题】:Find [R, C] in a 5*5 matrix of spiral order在一个 5*5 的螺旋顺序矩阵中找到 [R, C]
【发布时间】: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] - 你注意到什么了吗?

标签: c search matrix spiral


【解决方案1】:

我们将在这里使用递归。了解如果要搜索的元素不是NxN 螺旋矩阵的边界元素,那么我们可以移除边界并检查现在形成的(N-2)x(N-2) 螺旋矩阵中的元素。 以下代码使用此逻辑。 (注意RC 使用基于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));
    }
}

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2014-09-16
    • 2022-07-21
    • 1970-01-01
    相关资源
    最近更新 更多