Maximum decimal value path in a binary matrix
Last Updated :
24 Mar, 2023
Given binary square matrix [n*n]. Find maximum integer value in a path from top left to bottom right. We compute integer value using bits of traversed path. We start at index [0,0] and end at index [n-1][n-1]. from index [i, j], we can move [i, j+1] or [i+1, j].
Examples:
Input : mat[][] = {{1, 1, 0, 1},
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 1, 1}}
Output : 111
Explanation :
Path : (0,0) -> (0,1) -> (1,1) -> (1,2) ->
(2,2) -> (3,2) ->(3,3)
Decimal value : 1*(2^0) + 1*(2^1) + 1*(2^2) + 1*(2^3) +
0*(2^4) + 1*(2^5) + 1*(2^6) = 111
The above problem can be recursively defined as below:
// p indicates power of 2, initially p = i = j = 0
MaxDecimalValue(mat, i, j, p)
// If i or j is our of boundary
If i >= n || j >= n
return 0
// Compute rest of matrix find maximum decimal value
result max(MaxDecimalValue(mat, i, j+1, p+1),
MaxDecimalValue(mat, i+1, j, p+1))
If mat[i][j] == 1
return power(2, p) + result
Else
return result
Below is the implementation of above recursive algorithm.
C++
// C++ program to find maximum decimal value path in
// binary matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
long long int maxDecimalValue(int mat[][N], int i, int j,
int p)
{
// Out of matrix boundary
if (i >= N || j >= N )
return 0;
int result = max(maxDecimalValue(mat, i, j+1, p+1),
maxDecimalValue(mat, i+1, j, p+1));
// If current matrix value is 1 then return result +
// power(2, p) else result
if (mat[i][j] == 1)
return pow(2, p) + result;
else
return result;
}
//Driver program
int main()
{
int mat[][4] = {{ 1 ,1 ,0 ,1 },
{ 0 ,1 ,1 ,0 },
{ 1 ,0 ,0 ,1 },
{ 1 ,0 ,1 ,1 },
};
cout << maxDecimalValue(mat, 0, 0, 0) << endl;
return 0;
}
Java
// Java program to find maximum decimal value path in
// binary matrix
class GFG {
static final int N = 4;
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
static int maxDecimalValue(int mat[][], int i, int j,
int p) {
// Out of matrix boundary
if (i >= N || j >= N) {
return 0;
}
int result = Math.max(maxDecimalValue(mat, i, j + 1, p + 1),
maxDecimalValue(mat, i + 1, j, p + 1));
// If current matrix value is 1 then return result +
// power(2, p) else result
if (mat[i][j] == 1) {
return (int) (Math.pow(2, p) + result);
} else {
return result;
}
}
// Driver program
public static void main(String[] args) {
int mat[][] = {{1, 1, 0, 1},
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 1, 1},};
System.out.println(maxDecimalValue(mat, 0, 0, 0));
}
}
//this code contributed by Rajput-Ji
Python3
# Python3 program to find maximum decimal
# value path in binary matrix
N =4
# Returns maximum decimal value in binary
# matrix. Here p indicate power of 2
def maxDecimalValue(mat, i, j, p):
# Out of matrix boundary
if i >= N or j >= N:
return 0
result = max(
maxDecimalValue(mat, i, j+1, p+1),
maxDecimalValue(mat, i+1, j, p+1))
# If current matrix value is 1 then
# return result + power(2, p) else
# result
if mat[i][j] == 1:
return pow(2, p) + result
else:
return result
# Driver Program
mat = [ [1, 1, 0, 1],
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 1, 1] ]
print(maxDecimalValue(mat, 0, 0, 0))
# This code is contributed by Shrikant13.
C#
// C# program to find maximum decimal value path in
// binary matrix
using System;
class GFG {
static int N = 4;
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
static int maxDecimalValue(int[,] mat, int i,
int j,int p)
{
// Out of matrix boundary
if (i >= N || j >= N) {
return 0;
}
int result = Math.Max(maxDecimalValue(mat, i, j + 1, p + 1),
maxDecimalValue(mat, i + 1, j, p + 1));
// If current matrix value is 1 then return result +
// power(2, p) else result
if (mat[i,j] == 1)
{
return (int) (Math.Pow(2, p) + result);
} else
{
return result;
}
}
// Driver program
public static void Main() {
int[,] mat = {{1, 1, 0, 1},
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 1, 1},};
Console.Write(maxDecimalValue(mat, 0, 0, 0));
}
}
// This code is contributed by Ita_c.
PHP
<?php
// PHP program to find maximum
// decimal value path in binary
// matrix
// Returns maximum decimal value
// in binary matrix. Here p
// indicate power of 2
function maxDecimalValue($mat, $i,
$j, $p)
{
$N=4;
// Out of matrix boundary
if ($i >= $N || $j >= $N )
return 0;
$result = max(maxDecimalValue($mat, $i,
$j + 1, $p + 1),
maxDecimalValue($mat, $i + 1,
$j, $p + 1));
// If current matrix value
// is 1 then return result +
// power(2, p) else result
if ($mat[$i][$j] == 1)
return pow(2, $p) + $result;
else
return $result;
}
// Driver Code
$mat = array(array(1 ,1 ,0 ,1),
array(0 ,1 ,1 ,0),
array(1 ,0 ,0 ,1),
array(1 ,0 ,1 ,1));
echo maxDecimalValue($mat, 0, 0, 0) ;
// This code is contributed by nitin mittal.
?>
JavaScript
<script>
// JavaScript program to find maximum
// decimal value path in binary matrix
let N = 4;
// Returns maximum decimal value in
// binary matrix.Here p indicate power of 2
function maxDecimalValue(mat, i, j, p)
{
// Out of matrix boundary
if (i >= N || j >= N)
{
return 0;
}
let result = Math.max(maxDecimalValue(mat, i, j + 1,
p + 1),
maxDecimalValue(mat, i + 1, j,
p + 1));
// If current matrix value is 1 then
// return result + power(2, p) else result
if (mat[i][j] == 1)
{
return (Math.pow(2, p) + result);
}
else
{
return result;
}
}
// Driver Code
let mat = [ [ 1, 1, 0, 1 ],
[ 0, 1, 1, 0 ],
[ 1, 0, 0, 1 ],
[ 1, 0, 1, 1 ] ];
document.write(maxDecimalValue(mat, 0, 0, 0));
// This code is contributed by souravghosh0416
</script>
Output:
111
The time complexity of above recursive solution is exponential.
Space Complexity:O(1),since no extra space required.
Here matrix [3][3]
(2 2)
/ \
(1 2) (2 1)
/ \ / \
(0 2) (1 1) (1 1) (2 1)
/ \ / \ / \ / \
. . . . . . . .
. . . . . . . . and so no
If we see recursion tree of above recursive solution, we can observe overlapping sub-problems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution.
Below is the implementation of above problem using Dynamic Programming
C++
// C++ program to find Maximum decimal value Path in
// Binary matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
long long int MaximumDecimalValue(int mat[][N], int n)
{
int dp[n][n];
memset(dp, 0, sizeof(dp));
if (mat[0][0] == 1)
dp[0][0] = 1 ; // 1*(2^0)
// Compute binary stream of first row of matrix
// and store result in dp[0][i]
for (int i=1; i<n; i++)
{
// indicate 1*(2^i) + result of previous
if (mat[0][i] == 1)
dp[0][i] = dp[0][i-1] + pow(2, i);
// indicate 0*(2^i) + result of previous
else
dp[0][i] = dp[0][i-1];
}
// Compute binary stream of first column of matrix
// and store result in dp[i][0]
for (int i = 1 ; i <n ; i++ )
{
// indicate 1*(2^i) + result of previous
if (mat[i][0] == 1)
dp[i][0] = dp[i-1][0] + pow(2, i);
// indicate 0*(2^i) + result of previous
else
dp[i][0] = dp[i-1][0];
}
// Traversal rest Binary matrix and Compute maximum
// decimal value
for (int i=1 ; i < n ; i++ )
{
for (int j=1 ; j < n ; j++ )
{
// Here (i+j) indicate the current power of
// 2 in path that is 2^(i+j)
if (mat[i][j] == 1)
dp[i][j] = max(dp[i][j-1], dp[i-1][j]) +
pow(2, i+j);
else
dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
// Return maximum decimal value in binary matrix
return dp[n-1][n-1];
}
// Driver program
int main()
{
int mat[][4] = {{ 1 ,1 ,0 ,1 },
{ 0 ,1 ,1 ,0 },
{ 1 ,0 ,0 ,1 },
{ 1 ,0 ,1 ,1 },
};
cout << MaximumDecimalValue(mat, 4) << endl;
return 0;
}
Java
// Java program to find Maximum decimal value Path in
// Binary matrix
public class GFG {
final static int N = 4;
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
static int MaximumDecimalValue(int mat[][], int n) {
int dp[][] = new int[n][n];
if (mat[0][0] == 1) {
dp[0][0] = 1; // 1*(2^0)
}
// Compute binary stream of first row of matrix
// and store result in dp[0][i]
for (int i = 1; i < n; i++) {
// indicate 1*(2^i) + result of previous
if (mat[0][i] == 1) {
dp[0][i] = (int) (dp[0][i - 1] + Math.pow(2, i));
} // indicate 0*(2^i) + result of previous
else {
dp[0][i] = dp[0][i - 1];
}
}
// Compute binary stream of first column of matrix
// and store result in dp[i][0]
for (int i = 1; i < n; i++) {
// indicate 1*(2^i) + result of previous
if (mat[i][0] == 1) {
dp[i][0] = (int) (dp[i - 1][0] + Math.pow(2, i));
} // indicate 0*(2^i) + result of previous
else {
dp[i][0] = dp[i - 1][0];
}
}
// Traversal rest Binary matrix and Compute maximum
// decimal value
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
// Here (i+j) indicate the current power of
// 2 in path that is 2^(i+j)
if (mat[i][j] == 1) {
dp[i][j] = (int) (Math.max(dp[i][j - 1], dp[i - 1][j])
+ Math.pow(2, i + j));
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
// Return maximum decimal value in binary matrix
return dp[n - 1][n - 1];
}
// Driver program
public static void main(String[] args) {
int mat[][] = {{1, 1, 0, 1},
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 1, 1},};
System.out.println(MaximumDecimalValue(mat, 4));
}
}
/*This code is contributed by Rajput-Ji*/
Python3
# Python3 program to find Maximum decimal
# value Path in
# Binary matrix
N=4
# Returns maximum decimal value in binary matrix.
# Here p indicate power of 2
def MaximumDecimalValue(mat, n):
dp=[[0 for i in range(n)] for i in range(n)]
if (mat[0][0] == 1):
dp[0][0] = 1 # 1*(2^0)
# Compute binary stream of first row of matrix
# and store result in dp[0][i]
for i in range(1,n):
# indicate 1*(2^i) + result of previous
if (mat[0][i] == 1):
dp[0][i] = dp[0][i-1] + 2**i
# indicate 0*(2^i) + result of previous
else:
dp[0][i] = dp[0][i-1]
# Compute binary stream of first column of matrix
# and store result in dp[i][0]
for i in range(1,n):
# indicate 1*(2^i) + result of previous
if (mat[i][0] == 1):
dp[i][0] = dp[i-1][0] + 2**i
# indicate 0*(2^i) + result of previous
else:
dp[i][0] = dp[i-1][0]
# Traversal rest Binary matrix and Compute maximum
# decimal value
for i in range(1,n):
for j in range(1,n):
# Here (i+j) indicate the current power of
# 2 in path that is 2^(i+j)
if (mat[i][j] == 1):
dp[i][j] = max(dp[i][j-1], dp[i-1][j])+(2**(i+j))
else:
dp[i][j] = max(dp[i][j-1], dp[i-1][j])
# Return maximum decimal value in binary matrix
return dp[n-1][n-1]
# Driver program
if __name__=='__main__':
mat = [[ 1 ,1 ,0 ,1 ],
[ 0 ,1 ,1 ,0 ],
[ 1 ,0 ,0 ,1 ],
[ 1 ,0 ,1 ,1 ]]
print (MaximumDecimalValue(mat, 4))
#this code is contributed by sahilshelangia
C#
// C# program to find Maximum decimal value Path in
// Binary matrix
using System;
public class GFG {
readonly static int N = 4;
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
static int MaximumDecimalValue(int [,]mat, int n) {
int [,]dp = new int[n,n];
if (mat[0,0] == 1) {
dp[0,0] = 1; // 1*(2^0)
}
// Compute binary stream of first row of matrix
// and store result in dp[0,i]
for (int i = 1; i < n; i++) {
// indicate 1*(2^i) + result of previous
if (mat[0,i] == 1) {
dp[0,i] = (int) (dp[0,i - 1] + Math.Pow(2, i));
} // indicate 0*(2^i) + result of previous
else {
dp[0,i] = dp[0,i - 1];
}
}
// Compute binary stream of first column of matrix
// and store result in dp[i,0]
for (int i = 1; i < n; i++) {
// indicate 1*(2^i) + result of previous
if (mat[i,0] == 1) {
dp[i,0] = (int) (dp[i - 1,0] + Math.Pow(2, i));
} // indicate 0*(2^i) + result of previous
else {
dp[i,0] = dp[i - 1,0];
}
}
// Traversal rest Binary matrix and Compute maximum
// decimal value
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
// Here (i+j) indicate the current power of
// 2 in path that is 2^(i+j)
if (mat[i,j] == 1) {
dp[i,j] = (int) (Math.Max(dp[i,j - 1], dp[i - 1,j])
+ Math.Pow(2, i + j));
} else {
dp[i,j] = Math.Max(dp[i,j - 1], dp[i - 1,j]);
}
}
}
// Return maximum decimal value in binary matrix
return dp[n - 1,n - 1];
}
// Driver program
public static void Main() {
int [,]mat = {{1, 1, 0, 1},
{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 1, 1},};
Console.Write(MaximumDecimalValue(mat, 4));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find Maximum decimal value Path in
// Binary matrix
let N = 4;
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
function MaximumDecimalValue(mat,n)
{
let dp=new Array(n);
for(let i = 0; i < n; i++)
{
dp[i] = new Array(n);
for(let j = 0; j < n; j++)
{
dp[i][j] = 0;
}
}
if (mat[0][0] == 1) {
dp[0][0] = 1; // 1*(2^0)
}
// Compute binary stream of first row of matrix
// and store result in dp[0][i]
for (let i = 1; i < n; i++)
{
// indicate 1*(2^i) + result of previous
if (mat[0][i] == 1)
{
dp[0][i] = dp[0][i - 1] + Math.pow(2, i);
}
// indicate 0*(2^i) + result of previous
else
{
dp[0][i] = dp[0][i - 1];
}
}
// Compute binary stream of first column of matrix
// and store result in dp[i][0]
for (let i = 1; i < n; i++)
{
// indicate 1*(2^i) + result of previous
if (mat[i][0] == 1)
{
dp[i][0] = Math.floor(dp[i - 1][0] + Math.pow(2, i));
}
// indicate 0*(2^i) + result of previous
else
{
dp[i][0] = dp[i - 1][0];
}
}
// Traversal rest Binary matrix and Compute maximum
// decimal value
for (let i = 1; i < n; i++)
{
for (let j = 1; j < n; j++)
{
// Here (i+j) indicate the current power of
// 2 in path that is 2^(i+j)
if (mat[i][j] == 1)
{
dp[i][j] = Math.floor(Math.max(dp[i][j - 1], dp[i - 1][j])
+ Math.pow(2, i + j));
}
else
{
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
// Return maximum decimal value in binary matrix
return dp[n - 1][n - 1];
}
// Driver program
let mat = [[ 1 ,1 ,0 ,1 ],
[ 0 ,1 ,1 ,0 ],
[ 1 ,0 ,0 ,1 ],
[ 1 ,0 ,1 ,1 ]];
document.write(MaximumDecimalValue(mat, 4))
// This code is contributed by rag2127.
</script>
Output:
111
Time Complexity : O(n2)
Auxiliary space : O(n2)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read