Block Extraction
Problem Description
Aarya is playing with LEGO bricks, each a one-unit square. She connects the bricks to form various shapes, creating what is known as a block. Thus, a block is amalgamation of bricks in four possible directions: top, bottom, left, and right.
Each such block she created is assigned a unique identity number. Using the blocks she created, Aarya assembled a matrix with dimensions N x M. This matrix is positioned upright on the ground. Now, Aarya wants to pick up the block numbered K from the matrix, starting from the top. The rules to pick up the desired block are as follows
A block can be easily removed only if there are no other blocks on top of it.
It is guaranteed that there are no empty spaces within the matrix.
If block K is partially inside block L and can't be picked directly from the top, she will need to remove block L.
Given the front view of the matrix, determine how many blocks Aarya needs to remove to pick up the desired block with identity K.
Constraints
0 <= number of blocks <= 500
1 <= N, M <= 50
A block will never be fully enclosed by another block, meaning it won't be surrounded on all four sides.
Input
First line consists of two space separated integers, denoting N and M.
Next N lines consist of M space separated integers denoting the front view of the matrix assembled by Araya.
Last line consists of an integer K, denoting the identity number of the block which Aarya wants to pick up, from the top of the matrix.
Output
Print a single integer denoting the number of blocks she needs to remove to pick up the block with identity K.
Time Limit (secs)
1
Examples
Example 1
5 5
7 7 8 8 2
4 4 4 2 2
1 3 3 9 9
1 1 1 5 5
6 6 1 1 1
1
Output
7
Explanation
The matrix is 5 rows and 5 columns. It is composed of blocks with identities 1, 2, 3, 4, 5, 6, 7, 8 and 9. Aarya wishes to collect all blocks with identity 1. Note that block 1 is spanning across 3 different rows. Collecting a block should be understood as collecting all blocks with the same identity.
Thus, to collect all blocks numbered 1, we must collect it from rows 3, 4 and 5. To do so we need to remove all the blocks stacked above it. A careful look at the matrix tells us that apart from block 6 all other blocks will need to be removed to pick block 1.
Enumerating the blocks to be removed gives us the following list 2,3,4,5,7,8,9. This list contains 7 blocks. Hence print 7 as the output.
Example 2
Input
6 3
1 1 1
2 2 2
2 3 3
2 2 2
4 5 6
7 7 7
6
Output
3
Explanation
The matrix is 6 rows and 3 columns. It is composed of blocks with identities 1, 2, 3, 4, 5, 6, and 7. Aarya wishes to collect all blocks with identity 6. Note that block 6 is present in fifth row.
Thus, to collect block numbered 6, we must collect it from row 5. To do so we need to remove all the blocks stacked above it. A careful look at the matrix tells us that blocks 1,23 will need to be removed to pick block 6. Hence the output is 3.
Example 3
4 6
1 1 6 6 6 7
2 3 3 3 8 3
3 3 5 3 3 3
4 9 9 14 14 14
5
Output
6
Explanation
The matrix is 4 rows and 6 columns. It is composed of blocks with identities 1, 2, 3, 5, 6, 7, 8, 9 and 14. Aarya wishes to collect all blocks with identity 5. Note that block 5 is present in third row.
To pick up block number 5, we must remove all the blocks stacked above it. This means we need to remove the blocks numbered 1,2,3,6,7,8. Therefore, print 6 as output.

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {
    /**
     * Counts the number of unique blocks that need to be removed to extract all instances of block K.
     *
     * @param N      Number of rows in the matrix.
     * @param M      Number of columns in the matrix.
     * @param matrix 2D array representing the matrix of blocks.
     * @param K      The target block number to extract.
     * @return The count of unique blocks that need to be removed.
     */
    public static int countBlocksToRemove(int N, int M, int[][] matrix, int K) {
        Set<Integer> blocksToRemove = new HashSet<>(); // To store unique blocks that need to be removed
        for (int j = 0; j < M; j++) { // Iterate over each column
            for (int i = 0; i < N; i++) { // Iterate over each row in the column
                if (matrix[i][j] == K) {
                    // Collect all blocks above the current K in column j
                    for (int aboveI = 0; aboveI < i; aboveI++) {
                        int blockId = matrix[aboveI][j];
                        if (blockId != K) { // Exclude K itself
                            blocksToRemove.add(blockId);
                        }
                    }
                }
            }
        }
        return blocksToRemove.size();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read N and M
        int N = scanner.nextInt();
        int M = scanner.nextInt();
        scanner.nextLine(); // Consume the remaining newline
        // Initialize the matrix
        int[][] matrix = new int[N][M];
        // Read the matrix rows
        for (int i = 0; i < N; i++) {
            String[] rowInput;
            // Read the next non-empty line
            while (true) {
                String line = scanner.nextLine().trim();
                if (!line.isEmpty()) {
                    rowInput = line.split("\\s+");
                    break;
                }
            }
            // Parse the row into integers
            for (int j = 0; j < M; j++) {
                matrix[i][j] = Integer.parseInt(rowInput[j]);
            }
        }
        // Read the target block K
        int K;
        while (true) { // Ensure to read a non-empty line for K
            String line = scanner.nextLine().trim();
            if (!line.isEmpty()) {
                K = Integer.parseInt(line);
                break;
            }
        }
        scanner.close(); // Close the scanner as it's no longer needed
        // Compute the number of blocks to remove
        int result = countBlocksToRemove(N, M, matrix, K);
        // Print the result
        System.out.println(result);
    }
}

its coming as answer 2 for third input(example)