- codewithshiva

Latest

Search Bar

Tuesday, July 6, 2021

 2D Array and Product

Description

You are given an array of n rows, m columns which contains positive integers and  product P

You need to find occurrences of the product of three consecutive numbers (i.e x,y, and z )whose product is equal to given P appear horizontally, vertically and diagonally in the given matrix.

1592215892-cf2597c7eb-S2DSumcreenshot.png

Input

Input Format

First line: Three integers n, m and P where n denotes the number of rows, m denotes the number of columns in the matrix and P is the product.

Next line: Each line contains m characters which contain positive integers only.

Constraints

1< = n,m < 10

1<= P <=100


Output

Print the number of times the product p appears in the matrix

Sample Input 1 

3 3 6
3 2 1
2 2 2
1 5 1

Sample Output 1

3

Hint

Sample 1 Explanation

The product P 6 presents 3 times in the matrix(1 Horizontal +1 Vertical + 1 Diagonal)

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);


        int row = sc.nextInt();

        int col = sc.nextInt();

        int target = sc.nextInt();

        int[][] array = new int[row][col];


        for (int i = 0; i < row; i++) {

            for (int j = 0; j < col; j++) {

                array[i][j] = sc.nextInt();

            }

        }

        int count=0;

        


        

        for (int i=1;i<row-1;i++){

            for (int j=0;j<col;j++){

                if (array[i][j]*array[i-1][j]*array[i+1][j]==target){

                    count++;

                }

            }

        }

        for (int i=0;i<row;i++){

            for (int j=1;j<col-1;j++){

                if (array[i][j]*array[i][j-1]*array[i][j+1]==target){

                    count++;

                }

            }

        }


        for (int i=0;i<row-2;i++){

            for (int j=col-1;j>=2;j--){

                if (array[i][j]*array[i+1][j-1]*array[i+2][j-2]==target){

                    count++;

                }

            }

        }


        

        for (int i=0;i<row-2;i++){

            for (int j=0;j<col -2;j++){

                if (array[i][j]*array[i+1][j+1]*array[i+2][j+2]==target){

                    count++;

                }

            }

        }

        System.out.println(count);

    }

}

No comments:

Post a Comment