Open In App

Find the person who will finish last

Last Updated : 18 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary matrix mat[][] of dimensions M x N and two-person P1, P2, the task is to find the person who finishes last in choosing a 0 from the matrix which changes to 1 only if the row or column of the cell consisting of 0 has one or more than one 1 in the matrix. 

Note: P1 starts picking the 0s first and both the persons want to finish last. The given matrix will always have at least one 0 which could be chosen.

Examples:

Input: mat[][] = {{1, 0, 0}, {0, 0, 0}, {0, 0, 1}}
Output: P1
Explanation
P1 chooses mat[1][1], then the matrix becomes {{1, 0, 0}, {0, 1, 0}, {0, 0,1}}.
P2 has no 0 left to choose from. So, P1 finishes last.

Input: mat[][] = {{0, 0}, {0, 0}}
Output: P2
Explanation
No matter P1 chooses which 0 P2 will always have a 0 to choose and
after P2 picks a 0 there will not be any other 0 to choose from.

Approach: The idea is based on the observation that a 0 can’t be taken if either of its row or column has 1. Follow the steps below to solve this problem:

  • Initialize two sets, rows & cols to count the number of rows and columns which does not contain any 1.
  • Traverse the matrix and add rows and columns having 1 in it in the set.
  • Take the minimum number of rows or columns as if either of them becomes zero so that no more 0s can be taken.
  • After finding the minimum number of rows and columns available, if the number of choices made is odd then P1 finishes last otherwise, P2 finishes last.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the person
// who will finish last
void findLast(int mat[][3])
{
 
    int m = 3;
    int n = 3;
 
    // To keep track of rows
    // and columns having 1
    set<int> rows;
    set<int> cols;
 
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j]) {
                rows.insert(i);
                cols.insert(j);
            }
        }
    }
 
    // Available rows and columns
    int avRows = m - rows.size();
    int avCols = n - cols.size();
 
    // Minimum number of choices we have
    int choices = min(avRows, avCols);
 
    // If number of choices are odd
    if (choices & 1)
 
        // P1 will finish last
        cout << "P1";
 
    // Otherwise, P2 will finish last
    else
        cout << "P2";
}
 
// Given matrix
int main()
{
    int mat[][3]
        = { { 1, 0, 0 }, { 0, 0, 0 }, { 0, 0, 1 } };
 
    findLast(mat);
}
 
// This code is contributed by ukasp.


Java




// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
   
// Function to find the person
// who will finish last
static void findLast(int mat[][])
{
    int m = 3;
    int n = 3;
 
    // To keep track of rows
    // and columns having 1
    Set<Integer> rows = new HashSet<Integer>();
    Set<Integer> cols = new HashSet<Integer>();
     
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
        {
            if ((mat[i][j] > 0))
            {
                rows.add(i);
                cols.add(j);
            }
        }
    }
 
    // Available rows and columns
    int avRows = m - rows.size();
    int avCols = n - cols.size();
 
    // Minimum number of choices we have
    int choices = Math.min(avRows, avCols);
 
    // If number of choices are odd
    if ((choices & 1) != 0)
 
        // P1 will finish last
        System.out.println("P1");
 
    // Otherwise, P2 will finish last
    else
        System.out.println("P2");
}
 
// Driver code
public static void main (String[] args)
{
    int mat[][] = { { 1, 0, 0 },
                    { 0, 0, 0 },
                    { 0, 0, 1 } };
                     
    findLast(mat);
}
}
 
// This code is contributed by jana_sayantan


Python3




# Python3 program for the above approach
 
# Function to find the person
# who will finish last
def findLast(mat):
 
    m = len(mat)
    n = len(mat[0])
 
    # To keep track of rows
    # and columns having 1
    rows = set()
    cols = set()
 
    for i in range(m):
        for j in range(n):
            if mat[i][j]:
                rows.add(i)
                cols.add(j)
 
    # Available rows and columns
    avRows = m-len(list(rows))
    avCols = n-len(list(cols))
 
    # Minimum number of choices we have
    choices = min(avRows, avCols)
 
    # If number of choices are odd
    if choices & 1:
     
        # P1 will finish last
        print('P1')
 
    # Otherwise, P2 will finish last
    else:
        print('P2')
 
 
# Given matrix
mat = [[1, 0, 0], [0, 0, 0], [0, 0, 1]]
 
findLast(mat)


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find the person
// who will finish last
static void findLast(int[,] mat)
{
    int m = 3;
    int n = 3;
  
    // To keep track of rows
    // and columns having 1
    HashSet<int> rows = new HashSet<int>();
    HashSet<int> cols = new HashSet<int>();
      
    for(int i = 0; i < m; i++)
    {
        for(int j = 0; j < n; j++)
        {
            if ((mat[i,j] > 0))
            {
                rows.Add(i);
                cols.Add(j);
            }
        }
    }
  
    // Available rows and columns
    int avRows = m - rows.Count;
    int avCols = n - cols.Count;
  
    // Minimum number of choices we have
    int choices = Math.Min(avRows, avCols);
  
    // If number of choices are odd
    if ((choices & 1) != 0)
  
        // P1 will finish last
        Console.WriteLine("P1");
  
    // Otherwise, P2 will finish last
    else
        Console.WriteLine("P2");
}
  
// Driver code
static public void Main()
{
     
    int[,] mat = { { 1, 0, 0 },
                   { 0, 0, 0 },
                   { 0, 0, 1 } };
                  
    findLast(mat);
}
}
 
// This code is contributed by avanitrachhadiya2155


Javascript




<script>
 
        // Javascript program for the above approach
 
        // Function to find the person
        // who will finish last
        function findLast( mat)
        {
 
            let m = mat.length;
            let n = mat[0].length;
 
            // To keep track of rows
            // and columns having 1
            let rows = new Set();
            let cols = new Set();
 
            for (let i = 0; i < m; i++) {
                for (let j = 0; j < n; j++) {
                    if (mat[i][j]) {
                        rows.add(i);
                        cols.add(j);
                    }
                }
            }
 
            // Available rows and columns
            let avRows = m - rows.size;
            let avCols = n - cols.size;
 
            // Minimum number of choices we have
            let choices = Math.min(avRows, avCols);
 
            // If number of choices are odd
            if (choices & 1)
 
                // P1 will finish last
                document.write("P1")
 
            // Otherwise, P2 will finish last
            else
                document.write("P2")
        }
 
        // Given matrix
 
        let mat
            = [ [ 1, 0, 0], [ 0, 0, 0 ], [ 0, 0, 1 ]]
 
        findLast(mat);
 
        // This code is contributed by Hritik
         
    </script>


Output: 

P1

 

Time Complexity: O(M*N)
Auxiliary Space: O(M*N)



Similar Reads

Distribute M objects starting from Sth person such that every ith person gets arr[i] objects
Given an array arr[] consisting of N integers (1-based indexing) and two integers M and S, the task is to distribute M objects among N persons, starting from the position S, such that the ith person gets at most arr[i] objects each time. Examples: Input: arr[] = {2, 3, 2, 1, 4}, M = 11, S = 2Output: 1, 3, 2, 1, 4Explanation: The distribution of M (
8 min read
Number of hours after which the second person moves ahead of the first person if they travel at a given speed
Given three integers A, B and K. Initially, the first person was ahead of the second person by K kms. In every hour, the first person moves ahead by A kms and the second person moves ahead by B kms. The task is to print the number of hours after which the second person crosses the first. If it is impossible to do so then print -1. Examples: Input:
4 min read
Find out the person who got the ticket last.
N people from 1 to N are standing in the queue at a movie ticket counter. It is a weird counter, as it distributes tickets to the first K people and then the last K people and again the first K people, and so on, once a person gets a ticket moves out of the queue. The task is to find the last person to get the ticket. Examples: Input: N = 9, K = 3O
14 min read
Find minimum speed to finish all Jobs
Given an array A and an integer H where [Tex]1\leq A[i] \leq 10^{9} [/Tex]and [Tex]len(A) \leq H \leq 10^{9} [/Tex]. Each element A[i] represents remaining pending jobs to be done and H represents hours left to complete all of the jobs. The task is to find the minimum speed in jobs per Hour at which person needs to work to complete all jobs in H ho
9 min read
Find the time taken finish Processing of given processes
Given N processes and two arrays, arr1[] and arr2[] of size N each. arr1[] contains time spent by any process in critical section and arr2[] denotes time taken by a process to complete processing after coming out of the critical section. The task is to find the time taken by all the processes to complete their processing (both in critical section a
6 min read
Find minimum time to finish all jobs with given constraints
Given an array of jobs with different time requirements. There are K identical assignees available and we are also given how much time an assignee takes to do one unit of the job. Find the minimum time to finish all jobs with following constraints. An assignee can be assigned only contiguous jobs. For example, an assignee cannot be assigned jobs 1
12 min read
Construct the Rooted tree by using start and finish time of its DFS traversal
Given start and finish times of DFS traversal of N vertices that are available in a Rooted tree, the task is to construct the tree (Print the Parent of each node). Parent of the root node is 0.Examples: Input: Start[] = {2, 4, 1, 0, 3}, End[] = {3, 5, 4, 5, 4} Output: 3 4 4 0 3 Given Tree is -: 4(0, 5) / \ (1, 4)3 2(4, 5) / \ (2, 3)1 5(3, 4) The ro
8 min read
Minimum work to be done per day to finish given tasks within D days
Given an array task[] of size N denoting amount of work to be done for each task, the problem is to find the minimum amount of work to be done on each day so that all the tasks can be completed in at most D days. Note: On one day work can be done for only one task. Examples: Input: task[] = [3, 4, 7, 15], D = 10Output: 4Explanation: Here minimum wo
9 min read
Minimum time to finish tasks without skipping two consecutive
Given the time taken by n tasks. Find the minimum time needed to finish the tasks such that skipping of tasks is allowed, but can not skip two consecutive tasks. Examples : Input : arr[] = {10, 5, 7, 10} Output : 12 We can skip first and last task and finish these task in 12 min. Input : arr[] = {10} Output : 0 There is only one task and we can ski
10 min read
Check if it is possible to finish all task from given dependencies (Course Schedule I)
There are a total of N tasks, labeled from 0 to N-1. Some tasks may have prerequisites, for example to do task 0 you have to first complete task 1, which is expressed as a pair: [0, 1]. Given the total number of tasks N and a list of prerequisite pairs P, find if it is possible to finish all tasks. Examples: Input: N = 4, P = 3, prerequisites = {{1
16 min read
Article Tags :
Practice Tags :