📜  在给定的2D模式中找到第R行和第C列的元素

📅  最后修改于: 2021-04-23 15:53:29             🧑  作者: Mango

鉴于两个整数RC,任务是找到r行和C的元素。

图案:

例子:

简单方法:一种简单的解决方案是产生大小为R * C的图案矩阵,然后最终在r行和C返回元素。

时间复杂度: O(R * C)
辅助空间: O(R * C)

有效的方法:我们的想法是使用该公式找到r行的第一项\frac{R*(R+1)}{2}然后最后计算下使用循环的帮助,列任期。

下面是上述方法的实现:

C++
// C++ implementation to compute the
// R'th row and C'th column of the
// given pattern
  
#include 
using namespace std;
  
// Function to compute the
// R'th row and C'th column of the
// given pattern
int findValue(int R, int C)
{
  
    // First element of a given row
    int k = (R * (R - 1)) / 2 + 1;
  
    int diff = R + 1;
  
    // Element in the given column
    for (int i = 1; i < C; i++) {
        k = (k + diff);
        diff++;
    }
  
    return k;
}
  
// Driver Code
int main()
{
    int R = 4;
    int C = 4;
  
    // Function call
    int k = findValue(R, C);
  
    cout << k;
  
    return 0;
}


Java
// Java implementation to compute the 
// R'th row and C'th column of the 
// given pattern 
import java.io.*; 
  
class GFG{ 
      
// Function to compute the R'th 
// row and C'th column of the
// given pattern
static int findValue(int R, int C)
{
  
    // First element of a given row
    int k = (R * (R - 1)) / 2 + 1;
  
    int diff = R + 1;
  
    // Element in the given column
    for(int i = 1; i < C; i++)
    {
       k = (k + diff);
       diff++;
    }
    return k;
}
  
// Driver code 
public static void main (String[] args) 
{ 
    int R = 4;
    int C = 4;
  
    // Function call
    int k = findValue(R, C);
  
    System.out.println(k); 
} 
} 
  
// This code is contributed by mohit kumar 29


Python3
# Python3 implementation to find the 
# R'th row and C'th column value in 
# the given pattern
  
# Function to find the 
# R'th row and C'th column value in 
# the given pattern
def findValue(R, C):
  
    # First element of a given row
    k = (R*(R-1))//2 + 1
  
    diff = R + 1
  
    # Element in the given column
    for i in range(1, C):
        k = (k + diff)
        diff+= 1
  
    return k
  
# Driver Code
if __name__ == "__main__":
    R = 4
    C = 4
      
    k = findValue(R, C)
    print(k)


C#
// C# implementation to compute the 
// R'th row and C'th column of the 
// given pattern 
using System;
class GFG{ 
      
// Function to compute the R'th 
// row and C'th column of the
// given pattern
static int findValue(int R, int C)
{
  
    // First element of a given row
    int k = (R * (R - 1)) / 2 + 1;
  
    int diff = R + 1;
  
    // Element in the given column
    for(int i = 1; i < C; i++)
    {
        k = (k + diff);
        diff++;
    }
    return k;
}
  
// Driver code 
public static void Main() 
{ 
    int R = 4;
    int C = 4;
  
    // Function call
    int k = findValue(R, C);
  
    Console.Write(k); 
} 
} 
  
// This code is contributed by Code_Mech


输出:
25