C++ Program for Markov matrix
Given a m x n 2D matrix, check if it is a Markov Matrix.
Markov Matrix : The matrix in which the sum of each row is equal to 1.
Examples:
Input : 1 0 0 0.5 0 0.5 0 0 1 Output : yes Explanation : Sum of each row results to 1, therefore it is a Markov Matrix. Input : 1 0 0 0 0 2 1 0 0 Output : no
Approach: Initialize a 2D array, then take another single dimensional array to store the sum of each rows of the matrix, and check whether all the sum stored in this 1D array is equal to 1, if yes then it is Markov matrix else not.
C++
// C++ code to check Markov Matrix #include <iostream> using namespace std; #define n 3 bool checkMarkov( double m[][n]) { // outer loop to access rows // and inner to access columns for ( int i = 0; i <n; i++) { // Find sum of current row double sum = 0; for ( int j = 0; j < n; j++) sum = sum + m[i][j]; if (sum != 1) return false ; } return true ; } // Driver Code int main() { // Matrix to check double m[3][3] = { { 0, 0, 1 }, { 0.5, 0, 0.5 }, { 1, 0, 0 } }; // calls the function check() if (checkMarkov(m)) cout << " yes " ; else cout << " no " ; } // This code is contributed by Anant Agarwal. |
Output :
yes
Time Complexity: O(m*n), Here m is the number of rows and n is the number of columns.
Auxiliary Space: O(1), As constant extra space is used.
Please refer complete article on Program for Markov matrix for more details!