Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Recursion
  • Practice Recursion
  • MCQs on Recursion
  • Recursion Tutorial
  • Recursive Function
  • Recursion vs Iteration
  • Types of Recursions
  • Tail Recursion
  • Josephus Problem
  • Tower of Hanoi
  • Check Palindrome
Open In App
Next Article:
Count pairs in Array whose product is divisible by K
Next article icon

Count paths whose sum is not divisible by K in given Matrix

Last Updated : 21 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer matrix mat[][] of size M x N and an integer K, the task is to return the number of paths from top-left to bottom-right by moving only right and downwards such that the sum of the elements on the path is not divisible by K. 

Examples:

Input: mat = [[5, 2, 4], [3, 0, 5], [0, 7, 2]], K = 3
Output: 4

Input: mat = [[0], [0]], K = 7
Output: 0

Approach: The problem can be solved using recursion based on the following idea: 

    Step 1:

  • When we have reached the destination, check if the sum is not divisible by K, then we return 1.
  • When we have crossed the boundary of the matrix and we couldn’t find the right path, hence we return 0.

    Step 2: Try out all possible choices at a given index:

  • At every index we have two choices, one to go down and the other to go right. To go down, increase i by 1, and to move towards the right increase j by 1.

    Step 3: Count all ways:

  •   As we have to count all the possible unique paths, return the sum of all the choices (down and right) from each recursion.

Follow the steps mentioned below to implement the idea:

  • Create a recursive function.
  • For each call, there are two choices for the element as mentioned above.
  • Calculate the value of all possible cases as mentioned above.
  • The sum of all choices is the required answer.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function for calculating paths int solve(int i, int j, int local_sum,           vector<vector<int> >& grid, int k, int m, int n) {     // Base case     if (i > m - 1 || j > n - 1)         return 0;     if (i == m - 1 && j == n - 1) {         if ((local_sum + grid[i][j]) % k != 0)             return 1;         else             return 0;     }      // Choices of exploring paths     int right = solve(i, j + 1, (local_sum + grid[i][j]),                       grid, k, m, n);     int down = solve(i + 1, j, (local_sum + grid[i][j]),                      grid, k, m, n);      // Returning the sum of the choices     return (right + down); }  // Driver code int main() {     vector<vector<int> > mat         = { { 5, 2, 4 }, { 3, 0, 5 }, { 0, 7, 2 } };     int K = 3;      int M = mat.size();     int N = mat[0].size();      // Function call     int ways = solve(0, 0, 0, mat, K, M, N);     cout << ways << endl;     return 0; } 
Java
// java code to implement the approach import java.util.Scanner;  import java.io.*;  class GFG {    // Function for calculating paths public static int solve(int i, int j, int local_sum,          int[][] grid, int k, int m, int n) {     // Base case     if (i > m - 1 || j > n - 1)         return 0;     if (i == m - 1 && j == n - 1) {         if ((local_sum + grid[i][j]) % k != 0)             return 1;         else             return 0;     }      // Choices of exploring paths     int right = solve(i, j + 1, (local_sum + grid[i][j]),                       grid, k, m, n);     int down = solve(i + 1, j, (local_sum + grid[i][j]),                      grid, k, m, n);      // Returning the sum of the choices     return (right + down); }  // Driver code  public static void main(String[] args)  {            // System.out.println("Hello, World!");     int [][]mat         = { { 5, 2, 4 }, { 3, 0, 5 }, { 0, 7, 2 } };     int K = 3;      int M = mat.length;     int N = mat[0].length;      // Function call     int ways = solve(0, 0, 0, mat, K, M, N);     System.out.println(ways);      } }  // this code is contributed by ksam24000 
Python3
# Python code to implement the approach  # Function for calculating paths def solve(i, j, local_sum, grid, k, m, n):      # Base case     if (i > m - 1 or j > n - 1):         return 0     if (i == m - 1 and j == n - 1):         if ((local_sum + grid[i][j]) % k != 0):             return 1         else:             return 0      # Choices of exploring paths     right = solve(i, j + 1, (local_sum + grid[i][j]),                   grid, k, m, n)     down = solve(i + 1, j, (local_sum + grid[i][j]),                  grid, k, m, n)      # Returning the sum of the choices     return (right + down)  # Driver code mat = [[5, 2, 4], [3, 0, 5], [0, 7, 2]] K = 3  M = len(mat) N = len(mat[0])  # Function call ways = solve(0, 0, 0, mat, K, M, N) print(ways)  # This code is contributed by Saurabh Jaiswal 
C#
// C# code to implement the above approach using System; public class GFG {    // Function for calculating paths   public static int solve(int i, int j, int local_sum,                           int[,] grid, int k, int m, int n)   {      // Base case     if (i > m - 1 || j > n - 1)       return 0;     if (i == m - 1 && j == n - 1) {       if ((local_sum + grid[i,j]) % k != 0)         return 1;       else         return 0;     }      // Choices of exploring paths     int right = solve(i, j + 1, (local_sum + grid[i,j]),                       grid, k, m, n);     int down = solve(i + 1, j, (local_sum + grid[i,j]),                      grid, k, m, n);      // Returning the sum of the choices     return (right + down);   }    // Driver code   public static void Main(string[] args)   {      // System.out.println("Hello, World!");     int [,] mat = { { 5, 2, 4 }, { 3, 0, 5 }, { 0, 7, 2 } };     int K = 3;      int M = mat.GetLength(0);     int N = mat.GetLength(1);      // Function call     int ways = solve(0, 0, 0, mat, K, M, N);     Console.WriteLine(ways);   } }  // This code is contributed by AnkThon 
JavaScript
    <script>         // JavaScript code to implement the approach          // Function for calculating paths         const solve = (i, j, local_sum, grid, k, m, n) => {                      // Base case             if (i > m - 1 || j > n - 1)                 return 0;             if (i == m - 1 && j == n - 1) {                 if ((local_sum + grid[i][j]) % k != 0)                     return 1;                 else                     return 0;             }              // Choices of exploring paths             let right = solve(i, j + 1, (local_sum + grid[i][j]),                 grid, k, m, n);             let down = solve(i + 1, j, (local_sum + grid[i][j]),                 grid, k, m, n);              // Returning the sum of the choices             return (right + down);         }          // Driver code         let mat             = [[5, 2, 4], [3, 0, 5], [0, 7, 2]];         let K = 3;          let M = mat.length;         let N = mat[0].length;          // Function call         let ways = solve(0, 0, 0, mat, K, M, N);         document.write(ways)      // This code is contributed by rakeshsahni      </script> 

Output
4

Time Complexity: O((M+N-2)C(M-1)) as there can be this many paths
Auxiliary Space: O(N + M) recursion stack space as the path length is (M-1) + (N-1)

Efficient Approach (Using Memoization):

We can use Dynamic Programming to store the answer for overlapping subproblems. We can store the result for the current index i and j and the sum in the DP matrix.

The states of DP can be represented as follows:

  • DP[i][j][local_sum]

Below is the implementation of the above approach:

C++
// C++ code to implement the approach  #include <bits/stdc++.h> using namespace std;  // Function for calculating paths int solve(int i, int j, int local_sum,           vector<vector<int> >& grid, int k, int m, int n, vector<vector<vector<int>>> &dp) {     // Base case     if (i > m - 1 || j > n - 1)         return 0;     if (i == m - 1 && j == n - 1) {         if ((local_sum + grid[i][j]) % k != 0)             return 1;         else             return 0;     }          // If answer already stored return that     if(dp[i][j][local_sum] != -1) return dp[i][j][local_sum];      // Choices of exploring paths     int right = solve(i, j + 1, (local_sum + grid[i][j]) % k,                       grid, k, m, n, dp);     int down = solve(i + 1, j, (local_sum + grid[i][j]) % k,                      grid, k, m, n, dp);      // Returning the sum of the choices     return dp[i][j][local_sum] = (right + down); }  // Driver code int main() {     vector<vector<int> > mat         = { { 5, 2, 4 }, { 3, 0, 5 }, { 0, 7, 2 } };     int K = 3;      int M = mat.size();     int N = mat[0].size();           // 3d dp vector     vector<vector<vector<int>>> dp(M, vector<vector<int>>(N, vector<int>(K,-1)));      // Function call     int ways = solve(0, 0, 0, mat, K, M, N, dp);     cout << ways << endl;     return 0; } 
Java
// Java code to implement the approach import java.util.*;  public class GFG {    // Function for calculating paths   static int solve(int i, int j, int local_sum,                    int[][] grid, int k, int m, int n,                    int[][][] dp)   {          // Base case     if (i > m - 1 || j > n - 1)       return 0;     if (i == m - 1 && j == n - 1) {       if ((local_sum + grid[i][j]) % k != 0)         return 1;       else         return 0;     }      // If answer already stored return that     if (dp[i][j][local_sum] != -1)       return dp[i][j][local_sum];      // Choices of exploring paths     int right       = solve(i, j + 1, (local_sum + grid[i][j]) % k,               grid, k, m, n, dp);     int down       = solve(i + 1, j, (local_sum + grid[i][j]) % k,               grid, k, m, n, dp);      // Returning the sum of the choices     return dp[i][j][local_sum] = (right + down);   }    // Driver code   public static void main(String[] args)   {     int[][] mat       = { { 5, 2, 4 }, { 3, 0, 5 }, { 0, 7, 2 } };     int K = 3;      int M = mat.length;     int N = mat[0].length;      // 3d dp vector     int[][][] dp       = new int[M][N][K]; //(M, vector<vector<int>>(N,     // vector<int>(K,-1)));     for (int i = 0; i < M; i++) {       for (int j = 0; j < N; j++) {         for (int k = 0; k < K; k++) {           dp[i][j][k] = -1;         }       }     }      // Function call     int ways = solve(0, 0, 0, mat, K, M, N, dp);     System.out.println(ways);   } }  // This code is contributed by Karandeep1234 
Python3
def solve(i, j, local_sum, grid, k, m, n, dp):     # Base case     if i > m - 1 or j > n - 1:         return 0     if i == m - 1 and j == n - 1:         if (local_sum + grid[i][j]) % k != 0:             return 1         else:             return 0     # If answer already stored return that     if dp[i][j][local_sum] != -1:         return dp[i][j][local_sum]      # Choices of exploring paths     right = solve(i, j + 1, (local_sum + grid[i][j]) % k, grid, k, m, n, dp)     down = solve(i + 1, j, (local_sum + grid[i][j]) % k, grid, k, m, n, dp)      # Returning the sum of the choices     dp[i][j][local_sum] = (right + down)     return dp[i][j][local_sum]  # Driver code if __name__ == "__main__":     mat = [[5, 2, 4], [3, 0, 5], [0, 7, 2]]     K = 3     M = len(mat)     N = len(mat[0])      # 3d dp list     dp = [[[-1 for k in range(K)] for j in range(N)] for i in range(M)]      # Function call     ways = solve(0, 0, 0, mat, K, M, N, dp)     print(ways)  # This code is contributed by Vikram_Shirsat 
C#
using System;  class GFG {   // Function for calculating paths   static int Solve(int i, int j, int localSum,                    int[,] grid, int k, int m, int n,                    int[,,] dp)   {     // Base case     if (i > m - 1 || j > n - 1)       return 0;     if (i == m - 1 && j == n - 1) {       if ((localSum + grid[i, j]) % k != 0)         return 1;       else         return 0;     }      // If answer already stored return that     if (dp[i, j, localSum] != -1)       return dp[i, j, localSum];      // Choices of exploring paths     int right       = Solve(i, j + 1, (localSum + grid[i, j]) % k,               grid, k, m, n, dp);     int down       = Solve(i + 1, j, (localSum + grid[i, j]) % k,               grid, k, m, n, dp);      // Returning the sum of the choices     return dp[i, j, localSum] = (right + down);   }    // Driver code   static void Main(string[] args)   {     int[,] mat       = {{5, 2, 4}, {3, 0, 5}, {0, 7, 2}};     int K = 3;      int M = mat.GetLength(0);     int N = mat.GetLength(1);      // 3d dp array     int[,,] dp       = new int[M, N, K];     for (int i = 0; i < M; i++) {       for (int j = 0; j < N; j++) {         for (int k = 0; k < K; k++) {           dp[i, j, k] = -1;         }       }     }      // Function call     int ways = Solve(0, 0, 0, mat, K, M, N, dp);     Console.WriteLine(ways);   } } 
JavaScript
// Javascript code to implement the approach function solve(i, j, local_sum, grid, k, m, n, dp){ // Base case if (i > m - 1 || j > n - 1){ return 0; } if (i == m - 1 && j == n - 1){ if ((local_sum + grid[i][j]) % k !== 0){ return 1; } else{ return 0; } } // If answer already stored return that if (dp[i][j][local_sum] !== -1){ return dp[i][j][local_sum]; } // Choices of exploring paths let right = solve(i, j + 1, (local_sum + grid[i][j]) % k, grid, k, m, n, dp); let down = solve(i + 1, j, (local_sum + grid[i][j]) % k, grid, k, m, n, dp);  // Returning the sum of the choices dp[i][j][local_sum] = (right + down); return dp[i][j][local_sum]; }  // Driver code let mat = [[5, 2, 4], [3, 0, 5], [0, 7, 2]]; let K = 3; let M = mat.length; let N = mat[0].length;  // 3d dp list let dp = new Array(M); for(let i=0;i<M;i++){ dp[i] = new Array(N); for(let j=0;j<N;j++){ dp[i][j] = new Array(K).fill(-1); } }  // Function call let ways = solve(0, 0, 0, mat, K, M, N, dp); console.log(ways);  //This code is contributed by shivamsharma215 

Output
4

Time Complexity: O(m*n*k), where len is the length of the array
Auxiliary Space: O(m*n*k) 


Next Article
Count pairs in Array whose product is divisible by K

H

harsh2024it1034
Improve
Article Tags :
  • Matrix
  • Recursion
  • DSA
  • Amazon
Practice Tags :
  • Amazon
  • Matrix
  • Recursion

Similar Reads

  • Count pairs in array whose sum is divisible by K
    Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K. Note: This question is a generalized version of this Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 Explanation : There are five pairs possible whose sum
    10 min read
  • Count pairs in array whose sum is divisible by 4
    Given a array if 'n' positive integers. Count number of pairs of integers in the array that have the sum divisible by 4. Examples : Input: {2, 2, 1, 7, 5}Output: 3Explanation:Only three pairs are possible whose sumis divisible by '4' i.e., (2, 2), (1, 7) and (7, 5)Input: {2, 2, 3, 5, 6}Output: 4Reco
    10 min read
  • Count of pairs in Array whose product is divisible by K
    Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose product is divisible by K. Examples : Input: A[] = [1, 2, 3, 4, 5], K = 2Output: 7Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are(0, 1), (0, 3), (1, 2)
    9 min read
  • Count pairs in Array whose product is divisible by K
    Given a array vec and an integer K, count the number of pairs (i, j) such that vec[i]*vec[j] is divisible by K where i<j. Examples: Input: vec = {1, 2, 3, 4, 5, 6}, K = 4Output: 6Explanation: The pairs of indices (0, 3), (1, 3), (2, 3), (3, 4), (3, 5) and (1, 5) satisfy the condition as their pro
    11 min read
  • Count sub-arrays whose product is divisible by k
    Given an integer K and an array arr[], the task is to count all the sub-arrays whose product is divisible by K.Examples: Input: arr[] = {6, 2, 8}, K = 4 Output: 4 Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.Input: arr[] = {9, 1, 14}, K = 6 Output: 1 Naive approach: Run nested loops and
    15+ min read
  • Count sub-matrices having sum divisible 'k'
    Given a n x n matrix of integers and a positive integer k. The problem is to count all sub-matrices having sum divisible by the given value k. Examples: Input : mat[][] = { {5, -1, 6}, {-2, 3, 8}, {7, 4, -9} } k = 4 Output : 6 The index range for the sub-matrices are: (0, 0) to (0, 1) (1, 0) to (2,
    13 min read
  • Count Subarrays With Sum Divisible By K
    Given an array arr[] and an integer k, the task is to count all subarrays whose sum is divisible by k. Examples: Input: arr[] = [4, 5, 0, -2, -3, 1], k = 5Output: 7Explanation: There are 7 subarrays whose sum is divisible by 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and
    9 min read
  • Count subsets having product divisible by K
    Given an array arr[] of size N and an integer K, the task is to count the number of subsets from the given array with the product of elements divisible by K Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 60Output: 4Explanation: Subsets whose product of elements is divisible by K(= 60) are { {1, 2, 3,
    9 min read
  • Count number of pairs in array having sum divisible by K | SET 2
    Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose sum is divisible by K.Examples: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 There are five pairs possible whose sum Is divisible by '4' i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3)I
    6 min read
  • Count of submatrix with sum X in a given Matrix
    Given a matrix of size N x M and an integer X, the task is to find the number of sub-squares in the matrix with sum of elements equal to X.Examples: Input: N = 4, M = 5, X = 10, arr[][]={{2, 4, 3, 2, 10}, {3, 1, 1, 1, 5}, {1, 1, 2, 1, 4}, {2, 1, 1, 1, 3}} Output: 3 Explanation: {10}, {{2, 4}, {3, 1}
    15+ 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