Open In App

Exit Point in a Binary Matrix

Last Updated : 03 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary matrix of size N x M, you enter the matrix at cell (0, 0) in the left to the right direction. Whenever encountering a 0  retain in the same direction if encountered a 1 change direction to the right of the current direction and change that 1 value to 0,  find out exit point from the Matrix.

Examples: 

Input: matrix = {{0, 1, 0},

                          {0, 1, 1},

                          {0, 0, 0}}
Output: 1 0
Explanation: 
Enter the matrix at 0, 0 -> then move towards 0, 1 ->  1 is encountered -> turn right towards 1, 1 -> again 1 is encountered -> turn right again towards 1, 0 -> now, the boundary of matrix will be crossed ->hence, exit point reached at 1, 0.
 

Input: matrix = {{0, 0}}
Output: 0 1

 

Approach:  Since the matrix is entered at 0, 0 position the approach to solve this problem is based on the following observations

  • Initially, a matrix is entered at 0, 0 and moved towards the right.
  • As soon as 1 is encountered the direction is turned 90 degree clockwise i.e, right -> down -> left -> up.
  • Keep traversing the matrix in an above-mentioned manner till a boundary is reached.
  • As soon as the boundary is reached and no turn is encountered, the boundary will be crossed and the exit point will be the last cell traversed.

Illustration: 

Consider the matrix:
                           {{0, 1, 0}, 
                           {0, 1, 1}, 
                          {0, 0, 0}}
 

  • Traverse the matrix using row as i and column as j.
  • Initially the matrix is entered at 0, 0 and moved towards right ( (i, j) -> (i, j++) ) till 1 is encountered.
  • 1 is encountered at 0, 1. So, direction will be changed 90 degrees clockwise towards down ( (i, j) -> (i++, j) ).
  • Keep moving down till 1 is encountered at 1, 1
  • Again direction will be changed 90 degrees towards left ( (i, j) -> (i, j--) ).
  • Keep moving left.
  • No 1 is encountered now but the boundary of the matrix is crossed at 1, 0 and hence, 1, 0 is the required exit point.

Below is the implementation for the above-mentioned approach:

C++
// C++ program to find the exit point in a matrix

#include <bits/stdc++.h>
using namespace std;

// Function to find the exit
// point in a given matrix
vector<int> FindExitPoint(
    vector<vector<int> >& matrix)
{
    // initialization of row, column
    int i = 0, j = 0;
    int dir = 0;

    while (true) {
        dir = (dir + matrix[i][j]) % 4;

        // If a cell is traversed
        // then mark it has 0
        if (matrix[i][j] == 1) {
            matrix[i][j] = 0;
        }
        // Right direction
        if (dir == 0) {
            j++;
        }
        // Down direction
        else if (dir == 1) {
            i++;
        }
        // Left direction
        else if (dir == 2) {
            j--;
        }
        // Up direction
        else if (dir == 3) {
            i--;
        }

        // decrement either the row or col
        // since it crossed the boundary
        if (i < 0) {
            i++;
            break;
        }
        else if (i == matrix.size()) {
            i--;
            break;
        }
        else if (j < 0) {
            j++;
            break;
        }
        else if (j == matrix[0].size()) {
            j--;
            break;
        }
    }

    // return row and column
    vector<int> v{ i, j };
    return v;
}

// Driver Code
int main()
{
    vector<vector<int> > matrix{ { 0, 1, 0 },
                                 { 0, 1, 1 },
                                 { 0, 0, 0 } };
    vector<int> exitPoints = FindExitPoint(matrix);

    cout << exitPoints[0] << " " << exitPoints[1];

    return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {

  // Function to find the exit
  // point in a given matrix
  public static int[] FindExitPoint(int[][] matrix)
  {
    // initialization of row, column
    int i = 0, j = 0;
    int dir = 0;

    while (true) {
      dir = (dir + matrix[i][j]) % 4;

      // If a cell is traversed
      // then mark it has 0
      if (matrix[i][j] == 1) {
        matrix[i][j] = 0;
      }
      // Right direction
      if (dir == 0) {
        j++;
      }
      // Down direction
      else if (dir == 1) {
        i++;
      }
      // Left direction
      else if (dir == 2) {
        j--;
      }
      // Up direction
      else if (dir == 3) {
        i--;
      }

      // decrement either the row or col
      // since it crossed the boundary
      if (i < 0) {
        i++;
        break;
      }
      else if (i == matrix.length) {
        i--;
        break;
      }
      else if (j < 0) {
        j++;
        break;
      }
      else if (j == matrix[0].length) {
        j--;
        break;
      }
    }

    // return row and column
    int[] v = new int[] { i, j };
    return v;
  }

  // Driver Code
  public static void main(String[] args)
  {

    int[][] matrix = new int[][] { { 0, 1, 0 },
                                  { 0, 1, 1 },
                                  { 0, 0, 0 } };
    int[] exitPoints = FindExitPoint(matrix);

    System.out.println(exitPoints[0] + " "
                       + exitPoints[1]);

  }
}

// This code is contributed by rakeshsahni
Python3
 
# Python code for the above approach

# Function to find the exit
# point in a given matrix
def FindExitPoint(matrix) :

    # initialization of row, column
    i = 0
    j = 0;
    dir = 0;

    while (True):
        dir = (dir + matrix[i][j]) % 4;

        # If a cell is traversed
        # then mark it has 0
        if (matrix[i][j] == 1):
            matrix[i][j] = 0;

        # Right direction
        if (dir == 0):
            j += 1
        
        # Down direction
        elif (dir == 1):
            i += 1
    
        # Left direction
        elif (dir == 2):
            j -= 1

        # Up direction
        elif (dir == 3):
            i -= 1

        # decrement either the row or col
        # since it crossed the boundary
        if (i < 0):
            i += 1
            break;
        elif (i == len(matrix)):
            i -= 1
            break;

        elif (j < 0):
            j += 1
            break;
        
        elif (j == len(matrix[0])):
            j -= 1
            break

    # return row and column
    v = [i, j];
    return v

# Driver Code

matrix = [[0, 1, 0], [0, 1, 1], [0, 0, 0]];
exitPoints = FindExitPoint(matrix);

print(f"{exitPoints[0]} {exitPoints[1]}");


# This code is contributed by Saurabh Jaiswal
C#
// C# program for the above approach
using System;
class GFG {

  // Function to find the exit
  // point in a given matrix
  static int[] FindExitPoint(int[, ] matrix)
  {

    // initialization of row, column
    int i = 0, j = 0;
    int dir = 0;

    while (true) {
      dir = (dir + matrix[i, j]) % 4;

      // If a cell is traversed
      // then mark it has 0
      if (matrix[i, j] == 1) {
        matrix[i, j] = 0;
      }

      // Right direction
      if (dir == 0) {
        j++;
      }

      // Down direction
      else if (dir == 1) {
        i++;
      }

      // Left direction
      else if (dir == 2) {
        j--;
      }

      // Up direction
      else if (dir == 3) {
        i--;
      }

      // decrement either the row or col
      // since it crossed the boundary
      if (i < 0) {
        i++;
        break;
      }
      else if (i == matrix.GetLength(0)) {
        i--;
        break;
      }
      else if (j < 0) {
        j++;
        break;
      }
      else if (j == matrix.GetLength(1)) {
        j--;
        break;
      }
    }

    // return row and column
    int[] v = new int[] { i, j };
    return v;
  }

  // Driver Code
  public static void Main()
  {

    int[, ] matrix = new int[, ] { { 0, 1, 0 },
                                  { 0, 1, 1 },
                                  { 0, 0, 0 } };
    int[] exitPoints = FindExitPoint(matrix);

    Console.WriteLine(exitPoints[0] + " "
                      + exitPoints[1]);
  }
}

// This code is contributed by Samim Hossain Mondal.
JavaScript
 <script>
        // JavaScript code for the above approach

        // Function to find the exit
        // point in a given matrix
        function FindExitPoint(
            matrix) 
        {
        
            // initialization of row, column
            let i = 0, j = 0;
            let dir = 0;

            while (true) {
                dir = (dir + matrix[i][j]) % 4;

                // If a cell is traversed
                // then mark it has 0
                if (matrix[i][j] == 1) {
                    matrix[i][j] = 0;
                }
                // Right direction
                if (dir == 0) {
                    j++;
                }
                // Down direction
                else if (dir == 1) {
                    i++;
                }
                // Left direction
                else if (dir == 2) {
                    j--;
                }
                // Up direction
                else if (dir == 3) {
                    i--;
                }

                // decrement either the row or col
                // since it crossed the boundary
                if (i < 0) {
                    i++;
                    break;
                }
                else if (i == matrix.length) {
                    i--;
                    break;
                }
                else if (j < 0) {
                    j++;
                    break;
                }
                else if (j == matrix[0].length) {
                    j--;
                    break;
                }
            }

            // return row and column
            let v = [i, j];
            return v;
        }

        // Driver Code

        let matrix = [[0, 1, 0],
        [0, 1, 1],
        [0, 0, 0]];
        let exitPoints = FindExitPoint(matrix);

        document.write(exitPoints[0] + " " + exitPoints[1]);

       // This code is contributed by Potta Lokesh
    </script>

 
 


Output
1 0 


 

Time Complexity: O(NxM) where N is the number of rows and M is the number of columns.
Auxiliary Space: O(1)


 


Next Article
Article Tags :
Practice Tags :

Similar Reads