# Maximum decimal value path in a binary matrix in C++

C++Server Side ProgrammingProgramming

Given the task is to find the maximum integer value that can be obtained while travelling in a path from the top left element to the bottom right element of a given square binary array, that is, starting from index [0][0] to index [n - 1][n - 1].

While covering the path we can only move to right ([i][j + 1]) or to the bottom ([i + 1][j])

The integer value will be calculate using the bits of the traversed path.

Let’s now understand what we have to do using an example −

## Input

m = {
{1, 1, 1, 1},
{0, 0, 1, 0},
{1, 0, 1, 1},
{0, 1, 1, 1}
}

## Output

127

## Explanation

The path that we took is: [0, 0] →[0, 1] → [0, 2] → [1, 2] → [2, 2] → [3, 2] →[3, 3]

Therefore the decimal value becomes = 1*(20) + 1*(21) + 1*(22) + 1*(23) + 1*(24) + 1*(25) + 1*(26)

= 1 + 2 + 4 + 8 + 16 + 32 + 64

= 127

## Input

m = {
{1, 0, 1, 1},
{0, 0, 1, 0},
{1, 0, 0, 1},
{0, 1, 1, 1}
}

## Output

109

## Approach used in the below program as follows

• First define the size of side of the square matrix on the top using #define.

• In main() function create a 2D array int m[][4] to store the matrix and call Max(m, 0, 0, 0)

• In max() function first check if (i >= side || j >= side ). If so, then it means the we are out of the matrix boundary and return 0.

• Create a new variable int ans and put ans = max(Max(m, i, j+1, pw+1), Max(m, i+1, j, pw+1)).

• Then check if (m[i][j] == 1). If so, then return pow(2, pw) + ans.

• Else simply return ans.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
#define side 4
// pw is power of 2
int Max(int m[][side], int i, int j, int pw){
// Out of boundary
if (i >= side || j >= side )
return 0;
int ans = max(Max(m, i, j+1, pw+1), Max(m, i+1, j, pw+1));
if (m[i][j] == 1)
return pow(2, pw) + ans;
else
return ans;
}
//main function
int main(){
int m[][4] = {{1, 1, 1, 1},{0, 0, 1, 0},{1, 0, 1, 1},{0, 1, 1, 1}};
cout << Max(m, 0, 0, 0);
return 0;
}

## Output

127
Published on 04-Aug-2020 12:35:02