Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Farthest distance of a 0 from the center of a 2-D matrix
Next article icon

Farthest distance of a 0 from the center of a 2-D matrix

Last Updated : 09 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a matrix of odd order mat, the task is to find the farthest distance of a 0 from the center of the matrix. Distance between two elements at locations (i1, j1) and (i2, j2) of the matrix is calculated as |i1- i2| + |j1-j2|. If no 0 occurs in the matrix then print 0 as the result.

Examples: 

Input: mat[][] = {{2, 3, 0}, {0, 2, 0}, {0, 1, 1}} 
Output: 2

Input: mat[][] = {{2, 3, 4, {0, 2, 0}, {6, 1, 1}} 
Output: 1

Approach: 

The center of any matrix with odd order is at index i = j = floor(n/2). Now for finding the farthest distance of any 0 from the center, calculate the distance of each 0 from the center of the matrix as |i-n/2| + |j-n/2| and update the maximum distance as result. Print the result in the end or if the matrix doesn't contain any 0 then print 0.

Below is the implementation of the above approach: 
 

C++
// C++ program to find the farthest distance // of a 0 from the center of the matrix #include <bits/stdc++.h> #define n 3 using namespace std;  // function to return farthest distance // of zero from center of the matrix int farthestDistance(int matrix[][n]) {      int result = 0;      // traverse the matrix     for (int i = 0; i < n; i++) {         for (int j = 0; j < n; j++) {             if (matrix[i][j] == 0)                 result = max(result                            , abs(i - n/2) + abs(j - n/2));         }     }      // return result     return result; }  // driver program int main() {     int matrix[n][n] = { { 1, 2, 3 }                        , { 0, 1, 1 }                        , { 0, 0, 0 } };      cout << farthestDistance(matrix);     return 0; } 
Java
 //  Java program to find the farthest distance // of a 0 from the center of the matrix  import java.io.*;  class GFG {      static int n = 3;   // function to return farthest distance // of zero from center of the matrix static int farthestDistance(int matrix[][]) {      int result = 0;      // traverse the matrix     for (int i = 0; i < n; i++) {         for (int j = 0; j < n; j++) {             if (matrix[i][j] == 0)                 result = Math.max(result                         , Math.abs(i - n/2) + Math.abs(j - n/2));         }     }      // return result     return result; }  // driver program      public static void main (String[] args) {             int matrix[][] = { { 1, 2, 3 }                     , { 0, 1, 1 }                     , { 0, 0, 0 } };      System.out.print(farthestDistance(matrix));     } } // This code is contributed by anuj_67.. 
Python3
# Python3 program to find the farthest distance # of a 0 from the center of the matrix  n = 3  # function to return farthest distance # of zero from center of the matrix def farthestDistance(matrix):     result = 0      # traverse the matrix     for i in range (0, n):          for j in range (0, n):             if (matrix[i][j] == 0):                 result = max(result, abs(i - n // 2) +                                       abs(j - n//2))              # return result     return result  # Driver Code matrix = [[1, 2, 3],            [0, 1, 1],           [0, 0, 0]]  print(farthestDistance(matrix))  # This code is contributed by # Archana_kumari 
C#
// C# program to find the farthest distance  // of a 0 from the center of the matrix  using System;  class GFG {      static int n = 3;   // function to return farthest distance  // of zero from center of the matrix  static int farthestDistance(int [,]matrix)  {       int result = 0;       // traverse the matrix      for (int i = 0; i < n; i++)      {          for (int j = 0; j < n; j++)          {              if (matrix[i,j] == 0)                  result = Math.Max(result ,                          Math.Abs(i - n / 2) +                          Math.Abs(j - n / 2));          }      }       // return result      return result;  }   // Driver Code  static public void Main () {     int [,]matrix = {{ 1, 2, 3 },                       { 0, 1, 1 },                       { 0, 0, 0 }};       Console.WriteLine(farthestDistance(matrix));  }  }   // This code is contributed by Sachin  
PHP
<?php // PHP program to find the farthest distance  // of a 0 from the center of the matrix  $n = 3;   // function to return farthest distance  // of zero from center of the matrix  function farthestDistance($matrix)  {      global $n;      $result = 0;           // traverse the matrix      for ($i = 0; $i < $n; $i++)      {          for ($j = 0; $j < $n; $j++)         {              if (($matrix[$i][$j] == 0) > 0)                  $result = max($result,                            abs($i - $n / 2) +                            abs($j - $n / 2));          }      }       // return result      return $result;  }   // Driver Code $matrix = array(array( 1, 2, 3 ),                  array( 0, 1, 1 ),                 array( 0, 0, 0 ));   echo farthestDistance($matrix);       // This code is contributed by Sach_code ?> 
JavaScript
<script>  // Javascript program to find the farthest distance // of a 0 from the center of the matrix var n = 3;  // function to return farthest distance // of zero from center of the matrix function farthestDistance(matrix) {      var result = 0;      // traverse the matrix     for (var i = 0; i < n; i++) {         for (var j = 0; j < n; j++) {             if (matrix[i][j] == 0)                 result = Math.max(result                            , Math.abs(i - n/2) + Math.abs(j - n/2));         }     }      // return result     return result; }  // driver program var matrix = [ [ 1, 2, 3 ]                    , [ 0, 1, 1 ]                    , [ 0, 0, 0 ] ]; document.write( farthestDistance(matrix));  </script> 

Output
2

Complexity Analysis:

  • Time Complexity: O(N*M), as we are using nested loops to traverse N*M times.
  • Auxiliary Space: O(1), as we are not using any extra space for matrix.

Next Article
Farthest distance of a 0 from the center of a 2-D matrix

S

Shivam.Pradhan
Improve
Article Tags :
  • Matrix
  • Computer Science Fundamentals
  • DSA
Practice Tags :
  • Matrix

Similar Reads

    Farthest cell from a given cell in a Matrix
    Given the integers N, M, R and C where N and M denotes the number of rows and columns in a matrix and (R, C) denotes a cell in that matrix, the task is to find the distance of the farthest cell from the cell (R, C). Note: The matrix can only be traversed either horizontally or vertically at a time.
    6 min read
    Minimum Distance from a given Cell to all other Cells of a Matrix
    Given two integers R and C, denoting the number of rows and columns in a matrix, and two integers X and Y, the task is to find the minimum distance from the given cell to all other cells of the matrix. Examples: Input: R = 5, C = 5, X = 2, Y = 2 Output: 2 2 2 2 2 2 1 1 1 2 2 1 0 1 2 2 1 1 1 2 2 2 2
    9 min read
    Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix
    Given a Matrix of size N*N filled with 1's and 0's, the task is to find the maximum distance from a 0-cell to its nearest 1-cell. If the matrix is filled with only 0's or only 1's, return -1. Note: Only horizontal and vertical movements are allowed in the matrix. Examples: Input: mat[][] = {{0, 1, 0
    15+ min read
    Distance of nearest cell having 1 in a binary matrix
    Given a binary grid of n*m. Find the distance of the nearest 1 in the grid for each cell.The distance is calculated as |i1  - i2| + |j1 - j2|, where i1, j1 are the row number and column number of the current cell, and i2, j2 are the row number and column number of the nearest cell having value 1. Th
    15+ min read
    Shortest distance between two cells in a matrix or grid
    Given a 2D matrix mat[][] of size n × m. The task is to find the shortest distance from a source cell ('s') to a destination cell ('d'), by only moving through valid cells ('*'). We are not allowed to move through '0' cells, and movement is restricted to the four directions: up, down, left, and righ
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences