Cells in a matrix

You are given an integer N denoting an N×N matrix. Initially, each cell of the matrix is empty. You are given K tasks. In each task, you are given a cell (i,j) where cell (i,j) represents the ith row and jth column of the given matrix.

You have to perform each task sequentially in the given order. Each task is described in cell (i,j). For each task, you have to place X in each cell of row i and each cell column j. After you complete each task, you are required to print the number of empty cells in the matrix.

Example:

Input:  N=3, K=3, grid[][] = { { 1, 1 }, { 1, 3 }, { 3, 2 } };
Output: 4 2 0 

Approach

Java


public class CellsInMatrix {
    public static void main(String[] args) {
        int N = 3;
        int K = 3;

        boolean arr_row[] = new boolean[N];
        boolean arr_column[] = new boolean[N];
        int arr_row_remaining_blocks = N;
        int arr_column_remaining_blocks = N;
        int grid[][] = { { 11 }, { 13 }, { 32 } };
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < K; i++) {
            int row = grid[i][0] - 1;
            int column = grid[i][1] - 1;

            if (!arr_row[row]) {
                arr_row[row] = true;
                arr_row_remaining_blocks--;
            }

            if (!arr_column[column]) {
                arr_column[column] = true;
                arr_column_remaining_blocks--;
            }

            sb.append((long) arr_row_remaining_blocks * (long) arr_column_remaining_blocks + " ");
        }
        System.out.print(sb.toString());

    }
}


No comments:

Post a Comment