Matrix PDF
Matrix PDF
6 Bisymmetric matrix 69
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
1
Contents
19 Check if a grid can become row-wise and column-wise sorted after ad-
jacent swaps 164
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
20 Check if all rows of a matrix are circular rotations of each other 167
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
25 Check if sums of i-th row and i-th column are same in matrix 193
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
2
Contents
42 Count all possible paths from top left to bottom right of a mXn matrix 294
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
3
Contents
54 Count pairs from two sorted matrices with given sum 375
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
57 Count zeros in a row wise and column wise sorted matrix 419
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
4
Contents
74 Find a common element in all rows of a given row-wise sorted matrix 529
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
5
Contents
86 Find length of the longest consecutive path from a given starting character609
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
93 Find pair of rows in a binary matrix that has maximum bit difference 653
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
94 Find pairs with given sum such that elements of pair are in different rows658
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
6
Contents
98 Find size of the largest ‘+’ formed by all ones in a binary matrix 682
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
99 Find sum of all elements in a matrix except the elements in row and/or
column of given cell? 694
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
101 Find the largest area rectangular sub-matrix whose sum is equal to k 707
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
102 Find the largest rectangle of 1’s with swapping of columns allowed 712
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715
103 Find the longest path in a matrix with given constraints 716
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
109 Find whether there is path between two cells in matrix 764
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
110 Finding the maximum square sub-matrix with all equal elements 770
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
7
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
115 Given 1’s, 2’s, 3’s ……k’s print them in zig zag way. 810
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
116 Given a Boolean Matrix, find k such that all elements in k’th row are
0 and k’th column are 1. 819
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
117 Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’825
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836
118 Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded
by ‘X’ 837
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
119 Given an n x n square matrix, find sum of all sub-squares of size k x k 846
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859
129 Largest area rectangular sub-matrix with equal number of 1’s and 0’s 912
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916
8
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927
9
Contents
153 Maximum mirrors which can transfer light from bottom to right 1089
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1092
154 Maximum number of customers that can be satisfied with given quantity 1093
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1096
155 Maximum number of ones in a N*N matrix with given constraints 1097
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1102
157 Maximum path sum that starting with any cell of 0-th row and ending
with any cell of (N-1)-th row 1110
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1115
158 Maximum points collected by two persons allowed to meet once 1116
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1119
159 Maximum points from top left of matrix to bottom right and return
back 1120
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1125
10
Contents
163 Maximum sub-matrix area having count of 1’s one more than count of
0’s 1149
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1153
164 Maximum sum in a 2 x n grid such that no two elements are adjacent1154
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1157
165 Maximum sum of elements from each row in the matrix 1158
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1165
170 Maximum weight path ending at any element of last row in a matrix 1192
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1198
173 Minimum Cost Path with Left, Right, Bottom and Up moves allowed 1218
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1221
175 Minimum cells required to reach destination with jumps equal to cell
values 1228
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1236
176 Minimum cells traversed to reach corner where every cell represents
jumps 1237
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1239
177 Minimum changes needed to make a 3*3 matrix magic square 1240
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1242
11
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1246
183 Minimum operations required to make each row and column of matrix
equals 1280
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1287
184 Minimum operations required to set all elements of binary matrix 1288
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1293
186 Minimum queens required to cover all the squares of a chess board 1299
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1303
191 Move matrix elements in given direction and add elements with same
value 1333
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1356
193 Multiplication of two Matrices in Single line using Numpy in Python 1361
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1363
12
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1367
197 Number of cells a queen can move with obstacles on the chessborad 1381
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1389
201 Number of pair of positions in matrix which are not accessible 1408
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1410
204 Number of positions with Same address in row major and column
major order 1421
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1428
205 Operating System | Banker’s Algorithm : Print all the safe state (or
safe sequences) 1429
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1433
208 Performance analysis of Row major and Column major order of storing
arrays in C 1447
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1448
209 Place N^2 numbers in matrix such that every row has an equal sum 1449
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1451
13
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1457
219 Print a matrix in alternate manner (left to right then right to left) 1519
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1521
220 Print all elements in sorted order from row and column wise sorted
matrix 1522
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1527
222 Print all palindromic paths from top left to bottom right in a matrix 1532
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1534
223 Print all possible paths from top left to bottom right of a mXn matrix1535
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1538
14
Contents
233 Print the corner elements and their sum in a 2-D matrix 1612
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1617
15
Contents
16
Contents
262 Program to swap upper diagonal elements with lower diagonal elements
of matrix. 1824
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1829
264 Python List Equality | Program to check if two given matrices are
identical 1832
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1833
266 Python map function to find row with maximum number of 1’s 1836
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1837
269 Python | Print unique rows in a given boolean matrix using Set with
tuples 1844
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1845
274 Remove all outgoing edges except edge with minimum weight 1873
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1878
275 Removing row or column wise duplicates from matrix of characters 1879
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1883
276 Replace every matrix element with maximum of GCD of row or column 1884
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1889
17
Contents
282 Rotate a matrix by 90 degree without using any extra space | Set 2 1932
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1941
292 Search in a row wise and column wise sorted matrix 1994
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2001
18
Contents
302 Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists) 2057
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2062
303 Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys) 2063
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2069
19
Contents
314 Sum of matrix element where each elements is integer division of row
and column 2134
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2143
315 Sum of matrix in which each element is absolute difference of its row
and column numbers 2144
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2154
320 System of Linear Equations in three variables using Cramer’s Rule 2175
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2179
20
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2221
329 Ways of filling matrix such that product of all rows and all columns
are equal to unity 2236
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2242
331 heapq in Python to print all elements in sorted order from row and
column wise sorted matrix 2244
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2245
21
Chapter 1
Example 1
The matrix
1 0
0 0
should be changed to following
1 1
1 0
Example 2
The matrix
0 0 0
0 0 1
should be changed to following
0 0 1
1 1 1
Example 3
The matrix
1 0 0 1
0 0 1 0
0 0 0 0
should be changed to following
1 1 1 1
1 1 1 1
1 0 1 1
22
Chapter 1. A Boolean Matrix Question
C++
23
Chapter 1. A Boolean Matrix Question
}
}
}
// Modify the input matrix mat[] using the
// above constructed row[] and col[] arrays
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
if ( row[i] == 1 || col[j] == 1 )
{
mat[i][j] = 1;
}
}
}
}
/* A utility function to print a 2D matrix */
void printMatrix(bool mat[R][C])
{
int i, j;
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
cout << mat[i][j];
}
cout << endl;
}
}
// Driver Code
int main()
{
bool mat[R][C] = { {1, 0, 0, 1},
{0, 0, 1, 0},
{0, 0, 0, 0}};
cout << "Input Matrix \n";
printMatrix(mat);
modifyMatrix(mat);
printf("Matrix after modification \n");
printMatrix(mat);
return 0;
24
Chapter 1. A Boolean Matrix Question
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Java
25
Chapter 1. A Boolean Matrix Question
Python3
26
Chapter 1. A Boolean Matrix Question
R = 3
C = 4
def modifyMatrix(mat):
row = [0] * R
col = [0] * C
# Initialize all values of row[] as 0
for i in range(0, R):
row[i] = 0
# Initialize all values of col[] as 0
for i in range(0, C) :
col[i] = 0
# Store the rows and columns to be marked
# as 1 in row[] and col[] arrays respectively
for i in range(0, R) :
for j in range(0, C) :
if (mat[i][j] == 1) :
row[i] = 1
col[j] = 1
# Modify the input matrix mat[] using the
# above constructed row[] and col[] arrays
for i in range(0, R) :
for j in range(0, C):
if ( row[i] == 1 or col[j] == 1 ) :
mat[i][j] = 1
# A utility function to print a 2D matrix
def printMatrix(mat) :
for i in range(0, R):
for j in range(0, C) :
print(mat[i][j], end = " ")
print()
# Driver Code
mat = [ [1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0] ]
print("Input Matrix n")
printMatrix(mat)
27
Chapter 1. A Boolean Matrix Question
modifyMatrix(mat)
print("Matrix after modification n")
printMatrix(mat)
# This code is contributed by Nikita Tiwari.
C#
28
Chapter 1. A Boolean Matrix Question
row[i] = 1;
col[j] = 1;
}
}
}
/* Modify the input matrix
mat[] using the above
constructed row[] and
col[] arrays */
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
if (row[i] == 1 || col[j] == 1)
{
mat[i, j] = 1;
}
}
}
}
/* A utility function to
print a 2D matrix */
public static void printMatrix(int [,]mat,
int R, int C)
{
int i, j;
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
Console.Write(mat[i, j] + " ");
}
Console.WriteLine();
}
}
// Driver code
static public void Main ()
{
int [,]mat = {{1, 0, 0, 1},
{0, 0, 1, 0},
{0, 0, 0, 0}};
Console.WriteLine("Matrix Intially");
printMatrix(mat, 3, 4);
29
Chapter 1. A Boolean Matrix Question
modifyMatrix(mat, 3, 4);
Console.WriteLine("Matrix after "+
"modification n");
printMatrix(mat, 3, 4);
}
}
// This code is contributed by ajit
PHP
<?php
// PHP Code For A Boolean
// Matrix Question
$R = 3;
$C = 4;
function modifyMatrix(&$mat)
{
global $R,$C;
$row = array();
$col = array();
/* Initialize all values
of row[] as 0 */
for ($i = 0; $i < $R; $i++)
{
$row[$i] = 0;
}
/* Initialize all values
of col[] as 0 */
for ($i = 0; $i < $C; $i++)
{
$col[$i] = 0;
}
/* Store the rows and columns
to be marked as 1 in row[]
and col[] arrays respectively */
for ($i = 0; $i < $R; $i++)
{
for ($j = 0; $j < $C; $j++)
{
30
Chapter 1. A Boolean Matrix Question
if ($mat[$i][$j] == 1)
{
$row[$i] = 1;
$col[$j] = 1;
}
}
}
/* Modify the input matrix mat[]
using the above constructed
row[] and col[] arrays */
for ($i = 0; $i < $R; $i++)
{
for ($j = 0; $j < $C; $j++)
{
if ($row[$i] == 1 ||
$col[$j] == 1 )
{
$mat[$i][$j] = 1;
}
}
}
}
/* A utility function to
print a 2D matrix */
function printMatrix(&$mat)
{
global $R, $C;
for ($i = 0; $i < $R; $i++)
{
for ($j = 0; $j < $C; $j++)
{
echo $mat[$i][$j] . " ";
}
echo "\n";
}
}
// Driver code
$mat = array(array(1, 0, 0, 1),
array(0, 0, 1, 0),
array(0, 0, 0, 0));
echo "Input Matrix \n";
printMatrix($mat);
modifyMatrix($mat);
31
Chapter 1. A Boolean Matrix Question
echo "Matrix after modification \n";
printMatrix($mat);
// This code is contributed
// by ChitraNayal
?>
Output:
Input Matrix
1 0 0 1
0 0 1 0
0 0 0 0
Matrix after modification
1 1 1 1
1 1 1 1
1 0 1 1
C++
#include <bits/stdc++.h>
32
Chapter 1. A Boolean Matrix Question
33
Chapter 1. A Boolean Matrix Question
Java
class GFG
{
public static void modifyMatrix(int mat[][]){
// variables to check if there are any 1
// in first row and column
boolean row_flag = false;
boolean col_flag = false;
34
Chapter 1. A Boolean Matrix Question
// updating the first row and col if 1
// is encountered
for (int i = 0; i < mat.length; i++ ){
for (int j = 0; j < mat[0].length; j++){
if (i == 0 && mat[i][j] == 1)
row_flag = true;
if (j == 0 && mat[i][j] == 1)
col_flag = true;
if (mat[i][j] == 1){
mat[0][j] = 1;
mat[i][0] = 1;
}
}
}
// Modify the input matrix mat[] using the
// first row and first column of Matrix mat
for (int i = 1; i < mat.length; i ++){
for (int j = 1; j < mat[0].length; j ++){
if (mat[0][j] == 1 || mat[i][0] == 1){
mat[i][j] = 1;
}
}
}
// modify first row if there was any 1
if (row_flag == true){
for (int i = 0; i < mat[0].length; i++){
mat[0][i] = 1;
}
}
// modify first col if there was any 1
if (col_flag == true){
for (int i = 0; i < mat.length; i ++){
mat[i][0] = 1;
}
}
}
/* A utility function to print a 2D matrix */
public static void printMatrix(int mat[][]){
35
Chapter 1. A Boolean Matrix Question
Python3
36
Chapter 1. A Boolean Matrix Question
if (mat[i][j] == 1) :
mat[0][j] = 1
mat[i][0] = 1
# Modify the input matrix mat[] using the
# first row and first column of Matrix mat
for i in range(1, len(mat)) :
for j in range(1, len(mat) + 1) :
if (mat[0][j] == 1 or mat[i][0] == 1) :
mat[i][j] = 1
# modify first row if there was any 1
if (row_flag == True) :
for i in range(0, len(mat)) :
mat[0][i] = 1
# modify first col if there was any 1
if (col_flag == True) :
for i in range(0, len(mat)) :
mat[i][0] = 1
# A utility function to print a 2D matrix
def printMatrix(mat) :
for i in range(0, len(mat)) :
for j in range(0, len(mat) + 1) :
print( mat[i][j], end = "" )
print()
# Driver Code
mat = [ [1, 0, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0] ]
print("Input Matrix :")
printMatrix(mat)
modifyMatrix(mat)
print("Matrix After Modification :")
printMatrix(mat)
# This code is contributed by Nikita tiwari.
C#
37
Chapter 1. A Boolean Matrix Question
38
Chapter 1. A Boolean Matrix Question
if (mat[0, j] == 1 ||
mat[i, 0] == 1)
{
mat[i, j] = 1;
}
}
}
// modify first row
// if there was any 1
if (row_flag == true)
{
for (int i = 0;
i < mat.GetLength(1); i++)
{
mat[0, i] = 1;
}
}
// modify first col if
// there was any 1
if (col_flag == true)
{
for (int i = 0;
i < mat.GetLength(0); i ++)
{
mat[i, 0] = 1;
}
}
}
/* A utility function
to print a 2D matrix */
public static void printMatrix(int[,] mat)
{
for (int i = 0;
i < mat.GetLength(0); i ++)
{
for (int j = 0;
j < mat.GetLength(1); j ++)
{
Console.Write(mat[i, j] + " " );
}
Console.Write("\n");
}
}
39
Chapter 1. A Boolean Matrix Question
PHP
<?php
// PHP Code For A Boolean
// Matrix Question
$R = 3;
$C = 4;
function modifyMatrix(&$mat)
{
global $R, $C;
// variables to check if
// there are any 1 in
// first row and column
$row_flag = false;
$col_flag = false;
// updating the first
// row and col if 1
// is encountered
for ($i = 0; $i < $R; $i++)
{
for ($j = 0; $j < $C; $j++)
{
if ($i == 0 && $mat[$i][$j] == 1)
$row_flag = true;
40
Chapter 1. A Boolean Matrix Question
if ($j == 0 && $mat[$i][$j] == 1)
$col_flag = true;
if ($mat[$i][$j] == 1)
{
$mat[0][$j] = 1;
$mat[$i][0] = 1;
}
}
}
// Modify the input matrix
// mat[] using the first
// row and first column of
// Matrix mat
for ($i = 1; $i < $R; $i++)
{
for ($j = 1; $j < $C; $j++)
{
if ($mat[0][$j] == 1 ||
$mat[$i][0] == 1)
{
$mat[$i][$j] = 1;
}
}
}
// modify first row
// if there was any 1
if ($row_flag == true)
{
for ($i = 0; $i < $C; $i++)
{
$mat[0][$i] = 1;
}
}
// modify first col
// if there was any 1
if ($col_flag == true)
{
for ($i = 0; $i < $R; $i++)
{
$mat[$i][0] = 1;
}
}
}
41
Chapter 1. A Boolean Matrix Question
/* A utility function
to print a 2D matrix */
function printMatrix(&$mat)
{
global $R, $C;
for ($i = 0; $i < $R; $i++)
{
for ($j = 0; $j < $C; $j++)
{
echo $mat[$i][$j]." ";
}
echo "\n";
}
}
// Driver Code
$mat = array(array(1, 0, 0, 1 ),
array(0, 0, 1, 0 ),
array(0, 0, 0, 0 ));
echo "Input Matrix :\n";
printMatrix($mat);
modifyMatrix($mat);
echo "Matrix After Modification :\n";
printMatrix($mat);
// This code is conrtributed
// by ChitraNayal
?>
Output:
Input Matrix :
1001
0010
0000
Matrix After Modification :
1111
1111
1011
42
Chapter 1. A Boolean Matrix Question
Source
https://www.geeksforgeeks.org/a-boolean-matrix-question/
43
Chapter 2
C++
44
Chapter 2. A matrix probability question
45
Chapter 2. A matrix probability question
cout << "Probability is "
<< findProbability(m, n, i, j, N);
return 0;
}
Java
46
Chapter 2. A matrix probability question
y, N - 1) * 0.25;
// move right
prob += findProbability(m, n, x, y + 1,
N - 1) * 0.25;
// move down
prob += findProbability(m, n, x + 1,
y, N - 1) * 0.25;
// move left
prob += findProbability(m, n, x, y - 1,
N - 1) * 0.25;
return prob;
}
// Driver code
public static void main (String[] args)
{
// matrix size
int m = 5, n = 5;
// coordinates of starting point
int i = 1, j = 1;
// Number of steps
int N = 2;
System.out.println("Probability is " +
findProbability(m, n, i,
j, N));
}
}
// This code is contributed by KRV.
C#
47
Chapter 2. A matrix probability question
// check if (x, y) is valid
// matrix coordinate
static bool isSafe(int x, int y,
int m, int n)
{
return (x >= 0 && x < m &&
y >= 0 && y < n);
}
// Function to calculate probability
// that after N moves from a given
// position (x, y) in m x n matrix,
// boundaries of the matrix will
// not be crossed.
static double findProbability(int m, int n,
int x, int y,
int N)
{
// boundary crossed
if (! isSafe(x, y, m, n))
return 0.0;
// N steps taken
if (N == 0)
return 1.0;
// Initialize result
double prob = 0.0;
// move up
prob += findProbability(m, n, x - 1,
y, N - 1) * 0.25;
// move right
prob += findProbability(m, n, x, y + 1,
N - 1) * 0.25;
// move down
prob += findProbability(m, n, x + 1,
y, N - 1) * 0.25;
// move left
prob += findProbability(m, n, x, y - 1,
N - 1) * 0.25;
return prob;
48
Chapter 2. A matrix probability question
}
// Driver code
public static void Main ()
{
// matrix size
int m = 5, n = 5;
// coordinates of starting point
int i = 1, j = 1;
// Number of steps
int N = 2;
Console.Write("Probability is " +
findProbability(m, n, i,
j, N));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to find the probability
// that we do not cross boundary of a
// matrix after N moves.
// check if (x, y) is valid
// matrix coordinate
function isSafe($x, $y, $m, $n)
{
return ($x >= 0 && $x < $m &&
$y >= 0 && $y < $n);
}
// Function to calculate probability
// that after N moves from a given
// position (x, y) in m x n matrix,
// boundaries of the matrix will
// not be crossed.
function findProbability($m, $n, $x,
$y, $N)
{
// boundary crossed
49
Chapter 2. A matrix probability question
Output :
50
Chapter 2. A matrix probability question
Probability is 0.875
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : KRV, nitin mittal
Source
https://www.geeksforgeeks.org/a-matrix-probability-question/
51
Chapter 3
Input :
{{ 2, -2, -4},
mat= {-1, 3, 4},
{ 1, -2, -3}};
Output :
Symmetric matrix-
2 -1.5 -1.5
-1.5 3 1
-1.5 1 -3
Skew Symmetric Matrix-
0 -0.5 -2.5
0.5 0 3
2.5 -3 0
Explanation : The first matrix is symmetric as
transpose of it is same as the given matrix. The
52
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
Input:
{{5, 6, 8},
mat = {3, 4, 9},
{7, 2, 3}};
Output :
Symmetric matrix-
5 4.5 7.5
4.5 4 5.5
7.5 5.5 3
Skew Symmetric Matrix-
0 1.5 0.5
-1.5 0 3.5
-0.5 -3.5 0
C++
53
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
// else false.
bool isSkewSymmetric(float mat[N][N])
{
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] != -mat[j][i])
return false;
return true;
} */
void printMatrix(float mat[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
void printDistribution(float mat[N][N])
{
// tr is the transpose of matrix mat.
float tr[N][N];
// Find transpose of matrix.
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
tr[i][j] = mat[j][i];
// Declare two square matrix symm and
// skewsymm of size N.
float symm[N][N], skewsymm[N][N];
// Loop to find symmetric and skew symmetric
// and store it into symm and skewsymm matrix.
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
symm[i][j] = (mat[i][j] + tr[i][j]) / 2;
skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2;
}
}
cout << "Symmetric matrix-" << endl;
printMatrix(symm);
cout << "Skew Symmetric matrix-" << endl;
printMatrix(skewsymm);
}
54
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
// Driver function.
int main()
{
// mat is the N * N square matrix.
float mat[N][N] = { { 2, -2, -4 },
{ -1, 3, 4 },
{ 1, -2, -3 } };
printDistribution(mat);
return 0;
}
Java
55
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
// Loop to find symmetric and skew symmetric
// and store it into symm and skewsymm matrix.
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
symm[i][j] = (mat[i][j] + tr[i][j]) / 2;
skewsymm[i][j] = (mat[i][j] - tr[i][j]) / 2;
}
}
System.out.println("Symmetric matrix-" );
printMatrix(symm);
System.out.println("Skew Symmetric matrix-" );
printMatrix(skewsymm);
}
public static void main (String[] args) {
// mat is the N * N square matrix.
float mat[][] = { { 2, -2, -4 },
{ -1, 3, 4 },
{ 1, -2, -3 } };
printDistribution(mat);
}
}
// This code is contributed by Gitanjali.
C#
56
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
}
static void printDistribution(float[,] mat)
{
// tr is the transpose
// of matrix mat.
float[,] tr = new float[N, N];
// Find transpose of matrix.
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
tr[i, j] = mat[j, i];
// Declare two square matrix symm and
// skewsymm of size N.
float[,] symm = new float[N, N];
float[,] skewsymm = new float[N, N];
// Loop to find symmetric and skew symmetric
// and store it into symm and skewsymm matrix.
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
symm[i, j] = (mat[i, j] +
tr[i, j]) / 2;
skewsymm[i, j] = (mat[i, j] -
tr[i, j]) / 2;
}
}
System.Console.WriteLine("Symmetric matrix-" );
printMatrix(symm);
System.Console.WriteLine("Skew Symmetric matrix-" );
printMatrix(skewsymm);
}
// Driver code
public static void Main()
{
// mat is the N * N
// square matrix.
float[,] mat = new float[,]{{ 2, -2, -4},
{-1, 3, 4},
{1, -2, -3}};
printDistribution(mat);
}
57
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
}
// This code is contributed by mits.
PHP
<?php
// PHP program to distribute a
// square matrix into symmetric
// and skew symmetric matrix.
$N = 3;
function printMatrix($mat)
{
global $N;
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
echo $mat[$i][$j]. " ";
echo "\n";
}
}
function printDistribution($mat)
{
global $N;
// tr is the transpose
// of matrix mat.
$tr;
// Find transpose of matrix.
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
$tr[$i][$j] = $mat[$j][$i];
// Declare two square
// matrix symm and
// skewsymm of size N.
$symm;
$skewsymm;
// Loop to find symmetric
// and skew symmetric and
// store it into symm and
// skewsymm matrix.
for ($i = 0; $i < $N; $i++)
{
58
Chapter 3. A square matrix as sum of symmetric and skew-symmetric matrices
Output :
Symmetric matrix-
2 -1.5 -1.5
-1.5 3 1
-1.5 1 -3
Skew Symmetric matrix-
0 -0.5 -2.5
0.5 0 3
2.5 -3 0
Source
https://www.geeksforgeeks.org/a-square-matrix-as-sum-of-symmetric-and-skew-symmetric-matrices/
59
Chapter 4
60
Chapter 4. Addition and Subtraction of Matrix using pthreads
Examples:
Input :
Matrix A:
3 7 3 6
9 2 0 3
0 2 1 7
2 2 7 9
Matrix B:
6 5 5 2
1 7 9 6
6 6 8 9
0 3 5 2
Output :
61
Chapter 4. Addition and Subtraction of Matrix using pthreads
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// Value depend on System core
#define CORE 4
// Maximum matrix size
#define MAX 4
// Maximum threads is equal to total core of system
pthread_t thread[CORE * 2];
int mat_A[MAX][MAX], mat_B[MAX][MAX], sum[MAX][MAX], sub[MAX][MAX];
// Addition of a Matrix
void* addition(void* arg)
{
int i, j;
int core = (int)arg;
// Each thread computes 1/4th of matrix addition
for (i = core * MAX / 4; i < (core + 1) * MAX / 4; i++) {
for (j = 0; j < MAX; j++) {
// Compute Sum Row wise
sum[i][j] = mat_A[i][j] + mat_B[i][j];
}
}
}
// Subtraction of a Matrix
void* subtraction(void* arg)
{
int i, j;
62
Chapter 4. Addition and Subtraction of Matrix using pthreads
63
Chapter 4. Addition and Subtraction of Matrix using pthreads
printf("\nMatrix B:\n");
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf("%d ", mat_B[i][j]);
}
printf("\n");
}
// Creating threads equal
// to core size and compute matrix row
for (i = 0; i < CORE; i++) {
pthread_create(&thread[i], NULL, &addition, (void*)step);
pthread_create(&thread[i + CORE], NULL, &subtraction, (void*)step);
step++;
}
// Waiting for join threads after compute
for (i = 0; i < CORE * 2; i++) {
pthread_join(thread[i], NULL);
}
// Display Addition of mat_A and mat_B
printf("\n Sum of Matrix A and B:\n");
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
// Display Subtraction of mat_A and mat_B
printf("\n Subtraction of Matrix A and B:\n");
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
printf("%d ", sub[i][j]);
64
Chapter 4. Addition and Subtraction of Matrix using pthreads
}
printf("\n");
}
return 0;
}
Output:
Matrix A:
3 7 3 6
9 2 0 3
0 2 1 7
2 2 7 9
Matrix B:
6 5 5 2
1 7 9 6
6 6 8 9
0 3 5 2
9 12 8 8
10 9 9 9
6 8 9 16
2 5 12 11
-3 2 -2 4
8 -5 -9 -3
-6 -4 -7 -2
2 -1 2 7
Source
https://www.geeksforgeeks.org/addition-subtraction-matrix-using-pthreads/
65
Chapter 5
• The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x
– p1.x| + |p2.y – p1.y|.
• Find the total distance that needs to be traveled to reach the best meeting point (Total
distance traveled is minimum).
66
Chapter 5. Best meeting point in 2D binary array
Examples:
Steps :-
1) Store all horizontal and vertical positions of all group member.
2) Now sort it to find minimum middle position, which will be the best meeting point.
3) Find the distance of all members from best meeting point.
For example in above diagram, horizontal positions are {0, 2, 0} and vertical positions are
{0, 2, 4}. After sorting both, we get {0, 0, 2} and {0, 2, 4}. Middle point is (0, 2).
Note : Even no. of 1’s have two middle points, then also it works. Two middle points
means it have two best meeting points always. Both cases will give same distance. So we
will consider only one best meeting point to avoid the more overhead, Because our aim is
to find the distance only.
67
Chapter 5. Best meeting point in 2D binary array
}
}
// Sort positions so we can find most
// beneficial point
sort(vertical.begin(),vertical.end());
sort(horizontal.begin(),horizontal.end());
// middle position will always beneficial
// for all group members but it will be
// sorted which we have alredy done
int size = vertical.size()/2;
int x = vertical[size];
int y = horizontal[size];
// Now find total distance from best meeting
// point (x,y) using Manhattan Distance formula
int distance = 0;
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
if (grid[i][j] == 1)
distance += abs(x - i) + abs(y - j);
return distance;
}
// Driver program to test above functions
int main() {
int grid[ROW][COL] = {{1, 0, 1, 0, 1}, {0, 1, 0, 0, 0},{0, 1, 1, 0, 0}};
cout << minTotalDistance(grid);
return 0;
}
Output:
11
Source
https://www.geeksforgeeks.org/best-meeting-point-2d-binary-array/
68
Chapter 6
Bisymmetric matrix
Input : n = 3, m[][] = { { 1, 2, 3 },
{ 2, 5, 2 },
{ 3, 2, 1 } };
Output : Yes
Given matrix is symmetric along both the diagonal.
Input : n = 3, m[][] = { { 1, 2, 3 },
{ 9, 5, 2 },
{ 3, 2, 1 } };
Output : No
The idea is to check if the given matrix is symmetric along both the diagonal or not. For
diagonal from top-left to bottom-right, check if element at m[i][j] is equal to m[j][i]. For
diagonal from top-right to bottom-left, check if element at m[i][j] is equal to m[n – j – 1][n
– i – 1].
If both the above condition is true, then the given matrix is Bisymmetric matrix, otherwise
not.
C++
69
Chapter 6. Bisymmetric matrix
// matrix
#include <bits/stdc++.h>
using namespace std;
#define MAX 100
// Return if the given
// matrix is Bisymmetric matrix
bool checkBisymmetric(int m[][MAX],
int n)
{
// Checking Across
// Forward Diagonal
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
// check if corresponding
// position element are equal.
if (m[i][j] != m[j][i])
return false;
// Backward Diagonal
for (int i = 0; i < n; i++)
// for each column,
// upto main diagonal
for (int j = 0; j < n - i; j++)
// check if corresponding
// position element are equal.
if (m[i][j] != m[n - j - 1]
[n - i - 1])
return false;
return true;
}
// Driven Code
int main()
{
int n = 3;
int m[][MAX] = { { 1, 2, 3 },
{ 2, 5, 2 },
{ 3, 2, 1 } };
(checkBisymmetric(m, n) ? (cout << "Yes") :
(cout << "No"));
70
Chapter 6. Bisymmetric matrix
return 0;
}
Java
71
Chapter 6. Bisymmetric matrix
int m[][] = { { 1, 2, 3 },
{ 2, 5, 2 },
{ 3, 2, 1 } };
if(checkBisymmetric(m, n))
System.out.println( "Yes");
else
System.out.println( "No");
}
}
// This code is contributed by anuj_67.
Python3
72
Chapter 6. Bisymmetric matrix
n = 3;
m = [[ 1, 2, 3 ],
[ 2, 5, 2 ],
[ 3, 2, 1 ]]
if(checkBisymmetric(m, n)) :
print ("Yes")
else :
print ("No")
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
73
Chapter 6. Bisymmetric matrix
n - i - 1])
return false;
return true;
}
// Driven Code
public static void Main ()
{
int n = 3;
int [,]m = { { 1, 2, 3 },
{ 2, 5, 2 },
{ 3, 2, 1 } };
if(checkBisymmetric(m, n))
Console.WriteLine( "Yes");
else
Console.WriteLine( "No");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to check if a
// given matrix is Bisymmetric
// matrix
// MAX = 100;
// Return if the given matrix
// is Bisymmetric matrix
function checkBisymmetric($m, $n)
{
// Checking Across
// Forward Diagonal
for ( $i = 0; $i < $n; $i++)
for ( $j = 0; $j < $i; $j++)
// check if corresponding
// position element are equal.
if ($m[$i][$j] != $m[$j][$i])
return false;
74
Chapter 6. Bisymmetric matrix
Output :
Yes
Source
https://www.geeksforgeeks.org/bisymmetric-matrix/
75
Chapter 7
Input : 1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
Output : 1 2 3 4
5 8
1 4
5 6 7 8
The idea is really simple. We traverse given matrix. For every element being traversed,
we print it if it is a corner element. If it is not a corner element, then we print space character.
C++
76
Chapter 7. Boundary elements of a Matrix
if (i == 0)
cout << a[i][j] << " ";
else if (i == m-1)
cout << a[i][j] << " ";
else if (j == 0)
cout << a[i][j] << " ";
else if (j == n-1)
cout << a[i][j] << " ";
else
cout << " " << " ";
}
cout << "n";
}
}
// Driver code
int main()
{
int a[4][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 },
{ 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
printBoundary(a, 4, 4);
return 0;
}
Java
77
Chapter 7. Boundary elements of a Matrix
/* Driver program to test above function */
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 },
{ 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
printBoundary(a, 4, 4);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
C#
78
Chapter 7. Boundary elements of a Matrix
class GFG
{
public static void printBoundary(int [,]a,
int m,
int n)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (i == 0)
Console.Write(a[i, j] + " ");
else if (i == m - 1)
Console.Write(a[i, j] + " ");
else if (j == 0)
Console.Write(a[i, j] + " ");
else if (j == n - 1)
Console.Write(a[i, j] + " ");
else
Console.Write(" ");
}
Console.WriteLine(" ");
}
}
// Driver Code
static public void Main ()
{
int [,]a = {{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 }};
printBoundary(a, 4, 4);
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to print
// boundary element of
// matrix.
$MAX = 100;
79
Chapter 7. Boundary elements of a Matrix
Output:
1 2 3 4
5 8
1 4
5 6 7 8
80
Chapter 7. Boundary elements of a Matrix
Input : 1 2 3 4
5 6 7 8
1 2 3 4
5 6 7 8
Output : 54
C++
Java
81
Chapter 7. Boundary elements of a Matrix
public static long getBoundarySum(int a[][], int m,
int n)
{
long sum = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0)
sum += a[i][j];
else if (i == m-1)
sum += a[i][j];
else if (j == 0)
sum += a[i][j];
else if (j == n-1)
sum += a[i][j];
}
}
return sum;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 },
{ 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
long sum = getBoundarySum(a, 4, 4);
System.out.println("Sum of boundary elements"+
" is "+sum);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python
82
Chapter 7. Boundary elements of a Matrix
elif (j == 0):
sum += a[i][j]
elif (j == n-1):
sum += a[i][j]
return sum
# Driver code
a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ],
[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]
sum = printBoundary(a, 4, 4)
print "Sum of boundary elements is", sum
# This code is contributed by Sachin Bisht
C#
83
Chapter 7. Boundary elements of a Matrix
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 }};
long sum = getBoundarySum(a, 4, 4);
Console.WriteLine("Sum of boundary"+
" elements is "+
sum);
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to find
// sum of boundary
// elements of matrix.
function getBoundarySum($a,
$m, $n)
{
$sum = 0;
for ($i = 0; $i < $m; $i++)
{
for ( $j = 0; $j < $n; $j++)
{
if ($i == 0)
$sum += $a[$i][$j];
else if ($i == $m - 1)
$sum += $a[$i][$j];
else if ($j == 0)
$sum += $a[$i][$j];
else if ($j == $n - 1)
$sum += $a[$i][$j];
}
}
return $sum;
}
// Driver code
$a = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(1, 2, 3, 4),
array(5, 6, 7, 8));
$sum = getBoundarySum($a, 4, 4);
echo "Sum of boundary elements is ", $sum;
84
Chapter 7. Boundary elements of a Matrix
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/boundary-elements-matrix/
85
Chapter 8
Input : matrix: 0 5 -4
-5 0 1
4 -1 0
Output:
Transpose matrix: 0 -5 4
5 0 1
-4 1 0
Skew Symmetric matrix
Steps:
C++
86
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not
87
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not
int transpose_matrix[ROW][COL];
// Function create transpose matrix
transpose(transpose_matrix, matrix);
printf ("Transpose matrix: \n");
printMatrix(transpose_matrix);
// Check whether matrix is skew-symmetric or not
if (check(transpose_matrix, matrix))
printf("Skew Symmetric Matrix");
else
printf("Not Skew Symmetric Matrix");
return 0;
}
Java
88
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not
return true;
}
// Utility function to print a matrix
static void printMatrix(int matrix[][])
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
// Driver program to test above functions
public static void main (String[] args) {
int matrix[][] = {
{0, 5, -4},
{-5, 0, 1},
{4, -1, 0},
};
int transpose_matrix[][] = new int[ROW][COL];
// Function create transpose matrix
transpose(transpose_matrix, matrix);
System.out.println ("Transpose matrix: ");
printMatrix(transpose_matrix);
// Check whether matrix is skew-symmetric or not
if (check(transpose_matrix, matrix))
System.out.println("Skew Symmetric Matrix");
else
System.out.println("Not Skew Symmetric Matrix");
}
}
// This code is contributed by vt_m.
Python3
89
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not
COL=3
# Utility function to
# create transpose matrix
def transpose(transpose_matrix,matrix):
for i in range (ROW):
for j in range(COL):
transpose_matrix[j][i] = matrix[i][j]
# Utility function to
# check skew - symmetric
# matrix condition
def check(transpose_matrix,matrix):
for i in range(ROW):
for j in range(COL):
if (matrix[i][j] != -transpose_matrix[i][j]):
return False
return True
# Utility function to print a matrix
def printMatrix(matrix):
for i in range (ROW):
for j in range(COL):
print(matrix[i][j]," ",end="")
print()
# Driver program to test above functions
matrix= [
[0, 5, -4],
[-5, 0, 1],
[4, -1, 0],
]
transpose_matrix=[[0 for i in range(3)] for j in range(3)]
# Function create transpose matrix
transpose(transpose_matrix, matrix)
print("Transpose matrix:")
printMatrix(transpose_matrix)
# Check whether matrix is
# skew-symmetric or not
if (check(transpose_matrix, matrix)):
print("Skew Symmetric Matrix")
else:
print("Not Skew Symmetric Matrix")
# This code is contributed
# by Azkia Anam.
90
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not
C#
// C# program to check
// whether given matrix
// is skew-symmetric or not
using System;
class GFG
{
static int ROW =3;
static int COL =3;
// Utility function to
// create transpose matrix
static void transpose(int [,]transpose_matrix,
int [,]matrix)
{
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
transpose_matrix[j,i] = matrix[i,j];
}
// Utility function to check
// skew - symmetric matrix
// condition
static bool check(int [,]transpose_matrix,
int [,]matrix)
{
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COL; j++)
if (matrix[i, j] !=
-transpose_matrix[i, j])
return false;
return true;
}
// Utility function
// to print a matrix
static void printMatrix(int [,]matrix)
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
Console.Write(matrix[i, j] +
" ");
Console.WriteLine();
}
}
91
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not
// Driver Code
public static void Main ()
{
int [,]matrix = {{0, 5, -4},
{-5, 0, 1},
{4, -1, 0},};
int [,]transpose_matrix = new int[ROW, COL];
// Function create transpose matrix
transpose(transpose_matrix, matrix);
Console.WriteLine("Transpose matrix: ");
printMatrix(transpose_matrix);
// Check whether matrix is
// skew-symmetric or not
if (check(transpose_matrix, matrix))
Console.WriteLine("Skew Symmetric Matrix");
else
Console.WriteLine("Not Skew Symmetric Matrix");
}
}
// This code is contributed by anuj_67.
Output :
Transpose matrix:
0 -5 4
5 0 -1
-4 1 0
Skew Symmetric Matrix
References : Wikipedia
Improved By : vt_m
Source
https://www.geeksforgeeks.org/c-program-check-whether-matrix-skew-symmetric-not/
92
Chapter 9
#include <stdio.h>
#define N 4
// This function adds A[][] and B[][], and stores
// the result in C[][]
void add(int A[][N], int B[][N], int C[][N])
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
C[i][j] = A[i][j] + B[i][j];
}
int main()
{
int A[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int B[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
93
Chapter 9. C program for addition of two matrices
{4, 4, 4, 4}};
int C[N][N]; // To store result
int i, j;
add(A, B, C);
printf("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%d ", C[i][j]);
printf("\n");
}
return 0;
}
Java
94
Chapter 9. C program for addition of two matrices
// To store result
int C[][] = new int[N][N];
int i, j;
add(A, B, C);
System.out.print("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
System.out.print(C[i][j] + " ");
System.out.print("\n");
}
}
}
// This code is contributed by Anant Agarwal.
Python3
95
Chapter 9. C program for addition of two matrices
print("Result matrix is")
for i in range(N):
for j in range(N):
print(C[i][j], " ", end='')
print()
# This code is contributed
# by Anant Agarwal.
C#
96
Chapter 9. C program for addition of two matrices
Output:
Result matrix is
2 2 2 2
4 4 4 4
6 6 6 6
8 8 8 8
The program can be extended for rectangular matrices. The following post can be useful
for extending this program.
Source
https://www.geeksforgeeks.org/c-program-addition-two-matrices/
97
Chapter 10
#include <stdio.h>
#define N 4
// This function subtracts B[][] from A[][], and stores
// the result in C[][]
void multiply(int A[][N], int B[][N], int C[][N])
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
C[i][j] = A[i][j] - B[i][j];
}
int main()
{
int A[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int B[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
98
Chapter 10. C program for subtraction of matrices
{3, 3, 3, 3},
{4, 4, 4, 4}};
int C[N][N]; // To store result
int i, j;
multiply(A, B, C);
printf("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%d ", C[i][j]);
printf("\n");
}
return 0;
}
Java
99
Chapter 10. C program for subtraction of matrices
{4, 4, 4, 4}};
// To store result
int C[][]=new int[N][N];
int i, j;
multiply(A, B, C);
System.out.print("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
System.out.print(C[i][j] + " ");
System.out.print("\n");
}
}
}
// This code is contributed by Anant Agarwal.
Python3
100
Chapter 10. C program for subtraction of matrices
multiply(A, B, C)
print("Result matrix is")
for i in range(N):
for j in range(N):
print(C[i][j]," ",end='')
print()
# This code is contributed
# by Anant Agarwal.
Output:
Result matrix is
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
The program can be extended for rectangular matrices. The following post can be useful
for extending this program.
Source
https://www.geeksforgeeks.org/c-program-subtraction-matices/
101
Chapter 11
Examples:
Input : mat[][] = { 2 9 1 4 -2
6 7 2 11 4
4 2 9 2 4
1 9 2 4 4
0 2 4 2 5 }
Output :Yes
Explanation :
Sum of Half Diagonal 1 = 2 + 7 = 9
Sum of Half Diagonal 2 = 9 + 0 = 9
102
Chapter 11. Center element of matrix equals sums of half diagonals
Simple Approach:
Iterate two loops, find all half diagonal sums and then check all sums are equal to the center
element of the matrix or not. If any one of them is not equal to center element Then print
“No” Else “Yes”.
Time Complexity: O(N*N)
Efficient Approach : is based on Efficient approach to find diagonal sum in O(N).
Below are the Implementation of this approach
C++
103
Chapter 11. Center element of matrix equals sums of half diagonals
Java
104
Chapter 11. Center element of matrix equals sums of half diagonals
}
return (diag1_left == diag2_right &&
diag2_right == diag2_left &&
diag1_right == diag2_left &&
diag2_right == mat[n/2][n/2]);
}
// Driver code
public static void main(String args[])
{
int a[][] = { { 2, 9, 1, 4, -2},
{ 6, 7, 2, 11, 4},
{ 4, 2, 9, 2, 4},
{ 1, 9, 2, 4, 4},
{ 0, 2, 4, 2, 5} };
System.out.print ( HalfDiagonalSums(a, 5)
? "Yes" : "No" );
}
}
// This code is contributed by Sam007
C#
105
Chapter 11. Center element of matrix equals sums of half diagonals
PHP
<?php
// PHP Program to check if
// the center element is
// equal to the individual
// sum of all the half diagonals
$MAX = 100;
106
Chapter 11. Center element of matrix equals sums of half diagonals
// Function to Check center
// element is equal to the
// individual sum of all
// the half diagonals
function HalfDiagonalSums($mat, $n)
{
global $MAX ;
// Find sums of
// half diagonals
$diag1_left = 1; $diag1_right = 1;
$diag2_left = 1; $diag2_right = 1;
for ($i = 0, $j = $n - 1;
$i < $n; $i++, $j--)
{
if ($i < $n / 2)
{
$diag1_left += $mat[$i][$i];
$diag2_left += $mat[$j][$i];
}
else if ($i > $n / 2)
{
$diag1_right += $mat[$i][$i];
$diag2_right += $mat[$j][$i];
}
}
return ($diag1_left == $diag2_right &&
$diag2_right == $diag2_left &&
$diag1_right == $diag2_left &&
$diag2_right == $mat[$n / 2][$n / 2]);
}
// Driver code
$a = array(array(2, 9, 1, 4, -2),
array(6, 7, 2, 11, 4),
array(4, 2, 9, 2, 4),
array(1, 9, 2, 4, 4),
array(0, 2, 4, 2, 5));
if(HalfDiagonalSums($a, 5) == 0)
echo "Yes" ;
else
echo "No" ;
// This code is contributed
// by akt_mit
107
Chapter 11. Center element of matrix equals sums of half diagonals
?>
Output:
Yes
Source
https://www.geeksforgeeks.org/center-element-of-matrix-equals-sums-of-half-diagonals/
108
Chapter 12
Centrosymmetric Matrix
Examples:
Input : n = 3,
m[][] = { { 1, 3, 5 },
{ 6, 8, 6 },
{ 5, 3, 1 } };
Output : Yes
Input : n = 3,
m[][] = { { 1, 3, 5 },
{ 6, 8, 6 },
{ 5, 3, 0 } };
Output : No
The idea is to check for each element whether m[i][j] is equal to m[n – i – 1][n – j – 1]. If
any element does not satisfy the above condition, then print “No”, otherwise print “Yes”.
109
Chapter 12. Centrosymmetric Matrix
CPP
110
Chapter 12. Centrosymmetric Matrix
Java
111
Chapter 12. Centrosymmetric Matrix
if(checkCentrosymmetricted(n, m))
System.out.println( "Yes");
else
System.out.println( "No");
}
}
// This code is contributed by anuj_67.
C#
112
Chapter 12. Centrosymmetric Matrix
// Driven Program
public static void Main()
{
int n = 3;
int [,]m = { { 1, 3, 5 },
{ 6, 8, 6 },
{ 5, 3, 1 } };
if(checkCentrosymmetricted(n, m))
Console.WriteLine( "Yes");
else
Console.WriteLine( "No");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP Program to check whether given
// matrix is centrosymmetric or not.
//$N = 3;
function checkCentrosymmetricted( $n, $m)
{
$mid_row;
// Finding the middle row
// of the matrix
if ($n & 1)
$mid_row = $n / 2 + 1;
else
$mid_row = $n / 2;
// for each row upto middle row.
for($i = 0; $i < $mid_row; $i++)
{
// If each element and
// its corresponding
// element is not equal
// then return false.
for($j = 0; $j < $n; $j++) {
if ($m[$i][$j] != $m[$n - $i - 1]
[$n - $j - 1])
113
Chapter 12. Centrosymmetric Matrix
return false;
}
}
return true;
}
// Driver Code
$n = 3;
$m = array(array(1, 3, 5 ),
array( 6, 8, 6 ),
array( 5, 3, 1 ));
if(checkCentrosymmetricted($n, $m) )
echo "Yes" ;
else
echo "No";
// This code is contributed by anuj_67.
?>
Output
Yes
Complexity : O(N2 )
Improved By : vt_m
Source
https://www.geeksforgeeks.org/centrosymmetric-matrix/
114
Chapter 13
Approach :
A simple solution is to do BFS or DFS to find if there is a path.
A better solution is to mark all accessible nodes by changing their value to 1. First change
the value of first top left element value to 1 then in the first row get previous value and set
to current index in only first row if the value is -1 then no change then in first column do
the same.
115
Chapter 13. Check for possible path in 2D matrix
Then start from first row and first column and take previous row value and previous row
column and find max between them, and set to current index, if current index value is -1
then no change.
At the end if right bottom is 1 then return yes else return no.
C++
116
Chapter 13. Check for possible path in 2D matrix
Java
117
Chapter 13. Check for possible path in 2D matrix
}
//Driver code
public static void main(String[] args)
{
// Given array
int arr[][] = { { 0, 0, 0, -1, 0 },
{ -1, 0, 0, -1, -1 },
{ 0, 0, 0, -1, 0 },
{ -1, 0, -1, 0, -1 },
{ 0, 0, -1, 0, 0 } };
// path from arr[0][0]
// to arr[row][col]
if (isPath(arr))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed
// by prerna saini
C#
118
Chapter 13. Check for possible path in 2D matrix
PHP
<?php
// PHP program to find if
// there is path from top
// left to right bottom
$row = 5;
$col = 5;
// to find the path from
// top left to bottom right
function isPath($arr)
{
global $row, $col;
119
Chapter 13. Check for possible path in 2D matrix
$arr[0][0] = 1;
// Mark reachable (from
// top left) nodes in
// first row and first column.
for ($i = 1; $i < $row; $i++)
if ($arr[0][$i] != -1)
$arr[0][$i] = $arr[0][$i - 1];
for ($j = 1; $j < $col; $j++)
if ($arr[$j][0] != -1)
$arr[$j][0] = $arr[$j - 1][0];
// Mark reachable nodes
// in remaining matrix.
for ($i = 1; $i < $row; $i++)
for ($j = 1; $j < $col; $j++)
if ($arr[$i][$j] != -1)
$arr[$i][$j] = max($arr[$i][$j - 1],
$arr[$i - 1][$j]);
// return yes if right
// bottom index is 1
return ($arr[$row - 1][$col - 1] == 1);
}
// Driver Code
// Given array
$arr = array(array(0, 0, 0, 1, 0),
array(-1, 0, 0, -1, -1),
array(0, 0, 0, -1, 0),
array(-1, 0, -1, 0, -1),
array(0, 0, -1, 0, 0));
// path from arr[0][0]
// to arr[row][col]
if (isPath($arr))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67.
?>
Output:
120
Chapter 13. Check for possible path in 2D matrix
No
Source
https://www.geeksforgeeks.org/check-possible-path-2d-matrix/
121
Chapter 14
Input : n = 3
2 7 6
9 5 1
4 3 8
Output : Magic matrix
Explanation:In matrix sum of each
row and each column and diagonals sum is
same = 15.
Input : n = 3
1 2 3
4 5 6
7 8 9
Output : Not a Magic Matrix
Explanation:In matrix sum of each
row and each column and diagonals sum is
not same.
122
Chapter 14. Check given matrix is magic square or not
3. If the prime diagonal’s sum is equal to every row’s sum and every column’s sum, then its
magic matrix
Note : We do not need to calculate the sum of secondary diagonal because if the rows and
columns sum is equal too primary diagonal’s sum it means that secondary diagonal sum is
automatically equal.
C++
123
Chapter 14. Check given matrix is magic square or not
return false;
}
return true;
}
// driver program to
// test above function
int main()
{
int mat[][N] = {{ 2, 7, 6 },
{ 9, 5, 1 },
{ 4, 3, 8 }};
if (isMagicSquare(mat))
cout << "Magic Square";
else
cout << "Not a magic Square";
return 0;
}
Java
124
Chapter 14. Check given matrix is magic square or not
Python3
125
Chapter 14. Check given matrix is magic square or not
# Returns true if mat[][] is magic
# square, else returns false.
def isMagicSquare( mat) :
# calculate the sum of
# the prime diagonal
s = 0
for i in range(0, N) :
s = s + mat[i][i]
# For sums of Rows
for i in range(0, N) :
rowSum = 0;
for j in range(0, N) :
rowSum += mat[i][j]
# check if every row sum is
# equal to prime diagonal sum
if (rowSum != s) :
return False
# For sums of Columns
for i in range(0, N):
colSum = 0
for j in range(0, N) :
colSum += mat[j][i]
# check if every column sum is
# equal to prime diagonal sum
if (s != colSum) :
return False
return True
# Driver Code
mat = [ [ 2, 7, 6 ],
[ 9, 5, 1 ],
[ 4, 3, 8 ] ]
if (isMagicSquare(mat)) :
print( "Magic Square")
else :
print( "Not a magic Square")
# This code is contributed by Nikita Tiwari.
C#
126
Chapter 14. Check given matrix is magic square or not
127
Chapter 14. Check given matrix is magic square or not
}
// Driver Code
public static void Main()
{
int[,] mat =new int [,] {{ 2, 7, 6 },
{ 9, 5, 1 },
{ 4, 3, 8 }};
if (isMagicSquare(mat))
Console.WriteLine("Magic Square");
else
Console.WriteLine("Not a magic" +
" Square");
}
}
// This code is contributed by KRV.
PHP
<?php
// PHP program to check whether a given
// matrix is magic matrix or not
// Returns true if mat[][] is magic
// square, else returns false.
function isMagicSquare($mat)
{
// calculate the sum of
// the prime diagonal
$sum = 0; $N=3;
for($i = 0; $i < $N; $i++)
$sum = $sum + $mat[$i][$i];
// For sums of Rows
for($i = 0; $i < $N; $i++)
{
$rowSum = 0;
for ($j = 0; $j < $N; $j++)
$rowSum += $mat[$i][$j];
// check if every row sum is
// equal to prime diagonal sum
if ($rowSum != $sum)
return false;
128
Chapter 14. Check given matrix is magic square or not
}
// For sums of Columns
for ($i = 0; $i < $N; $i++)
{
$colSum = 0;
for ($j = 0; $j < $N; $j++)
$colSum += $mat[$j][$i];
// check if every column sum is
// equal to prime diagonal sum
if ($sum != $colSum)
return false;
}
return true;
}
// Driver Code
{
$mat = array(array(2, 7, 6),
array(9, 5, 1),
array(4, 3, 8));
if (isMagicSquare($mat))
echo "Magic Square";
else
echo "Not a magic Square";
return 0;
}
// This code is contributed by nitin mittal
?>
Magic square
Source
https://www.geeksforgeeks.org/check-given-matrix-is-magic-square-or-not/
129
Chapter 15
Input : N = 3 M = 3
0 1 0
0 0 0
0 1 0
Output : Both
First and third row are same and also second row
is in middle. So Horizontal Symmetric.
Similarly, First and third column are same and
also second column is in middle, so Vertical
Symmetric.
Input :
0 0 1
1 1 0
0 0 1.
Output : Horizontal
130
Chapter 15. Check horizontal and vertical symmetry in binary matrix
The idea is to use to pointers indicating two rows (or columns) and compare each cell of
both the pointed rows (or columns).
For Horizontal Symmetry, initialize one pointer i = 0 and another pointer j = N – 1.
Now, compare each element of i-th row and j-th row. Increase i by 1 and decrease j by 1 in
each loop cycle. If at least one not identical element is found, mark matrix as not horizontal
symmetric.
Similarly, for Vertical Symmetry, initialize one pointer i = 0 and another pointer j = M – 1.
Now, compare each element of i-th column and j-th column. Increase i by 1 and decrease j
by 1 in each loop cycle. If at least one not identical element is found, mark matrix as not
vertical symmetric.
Below is the implementation of above idea :
C++
131
Chapter 15. Check horizontal and vertical symmetry in binary matrix
{
// Checking each cell of a row.
for (int j = 0; j < N; j++)
{
// check if every cell is identical
if (arr[i][j] != arr[k][j])
{
horizontal = false;
break;
}
}
}
if (!horizontal && !vertical)
cout << "NO\n";
else if (horizontal && !vertical)
cout << "HORIZONTAL\n";
else if (vertical && !horizontal)
cout << "VERTICAL\n";
else cout << "BOTH\n";
}
// Driven Program
int main()
{
int mat[MAX][MAX] = { {1, 0, 1},
{0, 0, 0},
{1, 0, 1}};
checkHV(mat, 3, 3);
return 0;
}
Java
132
Chapter 15. Check horizontal and vertical symmetry in binary matrix
133
Chapter 15. Check horizontal and vertical symmetry in binary matrix
C#
// C# program to find if
// a matrix is symmetric.
using System;
public class GFG {
static void checkHV(int [,]arr, int N,
int M)
{
// Initializing as both horizontal
// and vertical symmetric.
bool horizontal = true;
bool vertical = true;
// Checking for Horizontal Symmetry.
// We compare first row with last
// row, second row with second
// last row and so on.
for (int i = 0, k = N - 1;
i < N / 2; i++, k--)
{
// Checking each cell of a column.
for (int j = 0; j < M; j++)
{
// check if every cell is identical
134
Chapter 15. Check horizontal and vertical symmetry in binary matrix
135
Chapter 15. Check horizontal and vertical symmetry in binary matrix
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find if
// a matrix is symmetric.
function checkHV($arr, $N, $M)
{
// Initializing as both horizontal
// and vertical symmetric.
$horizontal = true; $vertical = true;
// Checking for Horizontal Symmetry.
// We compare first row with last row,
// second row with second last row
// and so on.
for ($i = 0, $k = $N - 1;
$i < $N / 2; $i++,
$k--)
{
// Checking each cell of a column.
for ($j = 0; $j < $M; $j++)
{
// check if every cell is identical
if ($arr[$i][$j] != $arr[$k][$j])
{
$horizontal = false;
break;
}
}
}
// Checking for Vertical Symmetry.
// We compare first column with
// last column, second xolumn with
// second last column and so on.
for ($i = 0, $k = $M - 1;
$i < $M / 2; $i++,
$k--)
{
// Checking each cell of a row.
for ($j = 0; $j < $N; $j++)
{
136
Chapter 15. Check horizontal and vertical symmetry in binary matrix
Output :
BOTH
Source
https://www.geeksforgeeks.org/check-horizontal-vertical-symmetry-binary-matrix/
137
Chapter 16
where ‘In‘ denotes the n-by-n identity matrix. The matrix B is called the inverse matrix
of A.
A square matrix is Invertible if and only if its determinant is non-zero.
138
Chapter 16. Check if a Matrix is Invertible
Examples:
Input : {{1, 2, 3}
{4, 5, 6}
{7, 8, 9}}
Output : No
The given matrix is NOT Invertible
The value of Determinant is: 0
We find determinant of the matrix. Then we check if the determinant value is 0 or not. If
the value is 0, then we output, not invertible.
C++
139
Chapter 16. Check if a Matrix is Invertible
140
Chapter 16. Check if a Matrix is Invertible
Java
141
Chapter 16. Check if a Matrix is Invertible
142
Chapter 16. Check if a Matrix is Invertible
{3, 0, 0, 5 },
{2, 1, 4, -3 },
{1, 0, 5, 0 }};
if (isInvertible(mat, N))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed
// by ChitraNayal
Python 3
143
Chapter 16. Check if a Matrix is Invertible
C#
144
Chapter 16. Check if a Matrix is Invertible
// C# program to find
// Determinant of a matrix
using System;
class GFG
{
// Dimension of input
// square matrix
static int N = 4;
// Function to get cofactor of
// mat[p,q] in temp[,]. n is
// current dimension of mat[,]
static void getCofactor(int[,] mat, int[,] temp,
int p, int q, int n)
{
int i = 0, j = 0;
// Looping for each element
// of the matrix
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
// Copying into temporary matrix
// only those element which are
// not in given row and column
if (row != p && col != q)
{
temp[i, j++] = mat[row, col];
// Row is filled, so
// increase row index and
// reset col index
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
/* Recursive function for finding
determinant of matrix. n is current
dimension of mat[,]. */
145
Chapter 16. Check if a Matrix is Invertible
146
Chapter 16. Check if a Matrix is Invertible
else
Console.Write("No");
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP program to find Determinant
// of a matrix
// Dimension of input
// square matrix
$N = 4;
// Function to get cofactor of
// $mat[$p][$q] in $temp[][].
// $n is current dimension of $mat[][]
function getCofactor(&$mat, &$temp,
$p, $q, $n)
{
$i = 0;
$j = 0;
// Looping for each element
// of the matrix
for ($row = 0; $row < $n; $row++)
{
for ($col = 0; $col < $n; $col++)
{
// Copying into temporary matrix
// only those element which are
// not in given row and column
if ($row != $p && $col != $q)
{
$temp[$i][$j++] = $mat[$row][$col];
// Row is filled, so
// increase row index and
// reset col index
if ($j == $n - 1)
{
$j = 0;
$i++;
}
147
Chapter 16. Check if a Matrix is Invertible
}
}
}
}
/* Recursive function for finding
determinant of matrix. n is current
dimension of $mat[][]. */
function determinantOfMatrix(&$mat, $n)
{
$D = 0; // Initialize result
// Base case : if matrix
// contains single element
if ($n == 1)
return $mat[0][0];
$temp = array(array()); // To store cofactors
$sign = 1; // To store sign multiplier
// Iterate for each
// element of first row
for ($f = 0; $f < $n; $f++)
{
// Getting Cofactor of $mat[0][$f]
getCofactor($mat, $temp, 0, $f, $n);
$D += $sign * $mat[0][$f] *
determinantOfMatrix($temp, $n - 1);
// terms are to be added
// with alternate sign
$sign = -$sign;
}
return $D;
}
function isInvertible(&$mat, $n)
{
global $N;
if (determinantOfMatrix($mat, $N) != 0)
return true;
else
return false;
}
// Driver Code
148
Chapter 16. Check if a Matrix is Invertible
$mat = array(array(1, 0, 2, -1 ),
array(3, 0, 0, 5 ),
array(2, 1, 4, -3 ),
array(1, 0, 5, 0 ));
if (isInvertible($mat, $N))
echo "Yes";
else
echo "No";
// This code is contributed
// by ChitraNayal
?>
Output:
Yes
Improved By : ChitraNayal
Source
https://www.geeksforgeeks.org/check-if-a-matrix-is-invertible/
149
Chapter 17
Input : n = 4,
m[][] = {
{1, 2, 3, 5},
{2, 3, 5, 8},
{3, 5, 8, 0},
{5, 8, 0, 9}
};
Output : Yes
All diagonal {1}, {2, 2}, {3, 3, 3}, {5, 5, 5, 5}, {8, 8, 8}, {9} have constant
value.
So given matrix is Hankel Matrix.
Input : n = 3,
m[][] = {
{1, 2, 3},
{2, 3, 5},
{3, 9, 8}
};
Output : No
150
Chapter 17. Check if a given matrix is Hankel or not
a0 a1 a2 a3
a1 a2 a3 a4
a2 a3 a4 a5
a3 a4 a5 a6
Therefore, to check if the given matrix is Hankel Matrix, we need check if each m[i][j] ==
ai + j . Now, ai + j can be define as:
m[i+j][0], if i + j < n
ai + j =
m[i + j - n + 1][n-1], otherwise
C++
151
Chapter 17. Check if a given matrix is Hankel or not
return true;
}
// Drivers code
int main()
{
int n = 4;
int m[N][N] = {
{ 1, 2, 3, 5 },
{ 2, 3, 5, 8 },
{ 3, 5, 8, 0 },
{ 5, 8, 0, 9 }
};
checkHankelMatrix(n, m) ? (cout << "Yes")
: (cout << "No");
return 0;
}
Java
152
Chapter 17. Check if a given matrix is Hankel or not
Python 3
153
Chapter 17. Check if a given matrix is Hankel or not
C#
154
Chapter 17. Check if a given matrix is Hankel or not
155
Chapter 17. Check if a given matrix is Hankel or not
if(checkHankelMatrix(n, m))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Anuj_67.
PHP
<?php
// PHP Program to check if given matrix is
// Hankel Matrix or not.
$N = 4;
// Function to check if
// given matrix is Hankel
// Matrix or not.
function checkHankelMatrix( $n, $m)
{
// for each row
for($i = 0; $i < $n; $i++) {
// for each column
for ($j = 0;$j < $n; $j++) {
// checking if i + j
// is less than n
if ($i + $j < $n) {
// checking if the element
// is equal to the corresponding
// diagonal constant
if ($m[$i][$j] != $m[$i + $j][0])
return false;
}
else {
// checking if the element
// is equal to the
// corresponding diagonal constant
if ($m[$i][$j] != $m[$i + $j -
$n + 1][$n - 1])
return false;
}
156
Chapter 17. Check if a given matrix is Hankel or not
}
}
return true;
}
// Driver code
$n = 4;
$m = array(array( 1, 2, 3, 5 ),
array( 2, 3, 5, 8 ),
array( 3, 5, 8, 0 ),
array( 5, 8, 0, 9 ));
if(checkHankelMatrix($n, $m))
echo "Yes";
else
echo "No";
// This code is contributed by Anuj_67.
?>
Output:
Yes
Complexity : O(n + n)
Improved By : vt_m, Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/check-given-matrix-hankel-not/
157
Chapter 18
Input : 1 0 3
0 0 4
6 0 0
Output : Yes
There are 5 zeros. This count
is more than half of matrix
size.
Input : 1 2 3
0 7 8
5 0 7
Output: No
To check whether a matrix is sparse matrix we only need to check the total number of
elements that are equal to zero. If this count is more than (m * n)/2, we return true.
CPP
158
Chapter 18. Check if a given matrix is sparse or not
#include <iostream>
using namespace std;
const int MAX = 100;
bool isSparse(int array[][MAX], int m, int n)
{
int counter = 0;
// Count number of zeros in the matrix
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (array[i][j] == 0)
++counter;
return (counter > ((m * n) / 2));
}
// Driver Function
int main()
{
int array[][MAX] = { { 1, 0, 3 },
{ 0, 0, 4 },
{ 6, 0, 0 } };
int m = 3,
n = 3;
if (isSparse(array, m, n))
cout << "Yes";
else
cout << "No";
}
Java
159
Chapter 18. Check if a given matrix is sparse or not
// Count number of zeros in the matrix
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (array[i][j] == 0)
++counter;
return (counter > ((m * n) / 2));
}
// Driver Function
public static void main(String args[])
{
int array[][] = { { 1, 0, 3 },
{ 0, 0, 4 },
{ 6, 0, 0 } };
int m = 3,
n = 3;
if (isSparse(array, m, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by
// Nikita Tiwari.
Python3
160
Chapter 18. Check if a given matrix is sparse or not
C#
161
Chapter 18. Check if a given matrix is sparse or not
int m = 3,
n = 3;
if (isSparse(array, m, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to check if a matrix is
// sparse.
$MAX = 100;
function isSparse( $array, $m, $n)
{
$counter = 0;
// Count number of zeros
// in the matrix
for ($i = 0; $i < $m; ++$i)
for ($j = 0; $j < $n; ++$j)
if ($array[$i][$j] == 0)
++$counter;
return ($counter > (($m * $n) / 2));
}
// Driver Code
$array = array(array(1, 0, 3),
array(0, 0, 4),
array(6, 0, 0));
$m = 3;
$n = 3;
if (isSparse($array, $m, $n))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67.
?>
162
Chapter 18. Check if a given matrix is sparse or not
Output:
Yes
Improved By : vt_m
Source
https://www.geeksforgeeks.org/check-given-matrix-sparse-not/
163
Chapter 19
Check if a grid can become row-wise and column-wise sorted after adjacent swaps - Geeks-
forGeeks
Given a grid of size n x len filled with lowercase characters. We can swap two adjacent
characters in the same row and column. Now we have to check whether it is possible to
arrange in such a order that every row and every column in the grid is lexicographically
sorted.
Examples:
Input : abcde
fghij
olmkn
trpqs
xywuv
Output : Yes
Explanation :
The grid can be rearranged as
abcde
fghij
klmno
pqrst
uvwxy
The idea to do the above problem is really simple we can simply sort the characters in the
same row and then just
164
Chapter 19. Check if a grid can become row-wise and column-wise sorted after adjacent
swaps
check column vise if the new grid is sorted column vise or not. Please not that sorting is
possible with adjacent swaps (Bubble sort for example does only adjacent swaps)
The implementation of the above idea is given below.
C++
Python
165
Chapter 19. Check if a grid can become row-wise and column-wise sorted after adjacent
swaps
n = len(v)
for i in v:
i = ''.join(sorted(i))
for i in range(l - 1):
for j in range(n):
if (v[i][j] > v[i + 1][j]):
return False
return True
# Driver code
v = [ "ebcda", "ihgfj", "klmno", "pqrst", "yvwxu" ]
l = 5 # Length of strings
if check(v, l):
print "Yes"
else:
print "No"
# This code is contributed by Sachin Bisht
Output:
Yes
Source
https://www.geeksforgeeks.org/check-grid-can-become-row-wise-column-wise-sorted-adjacent-swaps/
166
Chapter 20
Check if all rows of a matrix are circular rotations of each other - GeeksforGeeks
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each
other or not.
Input: mat[][] = 1, 2, 3
3, 1, 2
2, 3, 1
Output: Yes
All rows are rotated permutation
of each other.
Input: mat[3][3] = 1, 2, 3
3, 2, 1
1, 3, 2
Output: No
Explanation : As 3, 2, 1 is not a rotated or
circular permutation of 1, 2, 3
1. Create a string of first row elements and concatenate the string with itself so that
string search operations can be efficiently performed. Let this string be str_cat.
2. Traverse all remaining rows. For every row being traversed, create a string str_curr
of current row elements. If str_curr is not a substring of str_cat, return false.
3. Return true.
167
Chapter 20. Check if all rows of a matrix are circular rotations of each other
168
Chapter 20. Check if all rows of a matrix are circular rotations of each other
{2, 3, 4, 1}
};
isPermutedMatrix(mat, n)? cout << "Yes" :
cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-rows-matrix-circular-rotations/
169
Chapter 21
Input:
[5 3 - - 7 - - - -]
[6 - - 1 9 5 - - -]
[- 9 8 - - - - 6 -]
[8 - - - 6 - - - 3]
[4 - - 8 - 3 - - 1]
[7 - - - 2 - - - 6]
[- 6 - - - - 2 8 -]
[- - - 4 1 9 - - 5]
[- - - - 8 - - 7 9]
Output: True
The basic idea is to check whether each row, column, and the 3×3 box is valid or not on
the basis of following points:
• The Sudoku board could be partially filled, where empty cells are filled with the
character ‘.’.
• An empty Sudoku board is also valid.
• A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells
need to be validated.
170
Chapter 21. Check if given Sudoku board configuration is valid or not
171
Chapter 21. Check if given Sudoku board configuration is valid or not
172
Chapter 21. Check if given Sudoku board configuration is valid or not
char board[9][9] = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' },
{ '6', '.', '.', '1', '9', '5', '.', '.', '.' },
{ '.', '9', '8', '.', '.', '.', '.', '6', '.' },
{ '8', '.', '.', '.', '6', '.', '.', '.', '3' },
{ '4', '.', '.', '8', '.', '3', '.', '.', '1' },
{ '7', '.', '.', '.', '2', '.', '.', '.', '6' },
{ '.', '6', '.', '.', '.', '.', '2', '8', '.' },
{ '.', '.', '.', '4', '1', '9', '.', '.', '5' },
{ '.', '.', '.', '.', '8', '.', '.', '7', '9' } };
cout << (isValidConfig(board, 9) ? "YES\n" : "NO\n");
return 0;
}
Output:
YES
Source
https://www.geeksforgeeks.org/check-if-given-sudoku-board-configuration-is-valid-or-not/
173
Chapter 22
Check if it is possible to make the given matrix increasing matrix or not - GeeksforGeeks
Given a matrix of N X M of positive integers, the task is to find out whether it is possible to
make the matrix increasing or not. Print the matrix constructed otherwise print -1. Matrix
elements should be greater than zero.
A matrix is said to be increasing matrix if:-
Examples:
Input : N = 4, M = 4
1223
1 -1 7 -1
6 -1 -1 -1
-1 -1 -1 -1
Output :
1223
1277
6677
6677
As we can see that this is the increasing matrix.
Input : N = 2, M = 3
1 4 -1
1 -1 3
174
Chapter 22. Check if it is possible to make the given matrix increasing matrix or not
Output : -1
Here, in the first row, we have to put something greater
than 4 to make it increasing sequence. But, after this,
the 3rd column will never be in increasing order.
So, it is impossible to make it increasing matrix.
This implies that dp[i][j] >= dp[r] for every 1 <= r <= i, 1 <= c <= j (one element is
greater than all the elements that are up to the left).
Let i be the first row of dp that contains a -1 and in this row let j be the column of the
leftmost -1. It is always convenient to replace dp[i][j] with the minimum possible value,
otherwise, it may be impossible to find a valid value for another -1 that is down to the
right. So one possible solution (and the lexicographically smallest) is to set dp[i][j] = max
{ dp[i][j-1], dp[i-1][j] }.
After filling some of the unknown positions in dp, it may turn out that one of the values
of dp is smaller than some of the elements that are up to the left. In this case, there is no
solution.
175
Chapter 22. Check if it is possible to make the given matrix increasing matrix or not
dp[i][j] = b;
// If dp[i][j] is less than from it's left
// element or from it's upper element
else if (dp[i][j] < b)
flag = true;
}
}
// If it is not possible
if (flag)
cout << -1 << '\n';
else {
// Printing the increasing matrix
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cout << dp[i][j] << ' ';
}
cout << endl;
}
}
}
// Drivers code
int main()
{
/* Here the matrix is 1 2 3 3
1 -1 7 -1
6 -1 -1 -1
-1 -1 -1 -1
Putting 0 in first row & column */
int dp[n + 1][m + 1] = { { 0, 0, 0, 0, 0 },
{ 0, 1, 2, 2, 3 },
{ 0, 1, -1, 7, -1 },
{ 0, 6, -1, -1, -1 },
{ 0, -1, -1, -1, -1 } };
findIncreasingMatrix(dp);
}
Output:
1 2 2 3
1 2 7 7
176
Chapter 22. Check if it is possible to make the given matrix increasing matrix or not
6 6 7 7
6 6 7 7
Source
https://www.geeksforgeeks.org/check-possible-make-given-matrix-increasing-matrix-not/
177
Chapter 23
Input : N = 3, M = 3, K = 7
mat[][] = { { 2, 3, 1 },
{ 6, 1, 9 },
{ 8, 2, 3 } };
Output : 6
Path (1, 1) -> (2, 2) -> (3, 3) to complete
journey to absorb 6 value.
Input : N = 3, M = 4, K = 9
mat[][] = {
{ 2, 3, 4, 1 },
{ 6, 5, 5, 3 },
{ 5, 2, 3, 4 }
};
Output : -1
178
Chapter 23. Check if possible to cross the matrix with given power
• Declare a boolean 3D matrix, say dp[ ][ ][ ], with N*M*(K+1) dimension such that
dp[ i ][ j ][ k ] is true if it possible to reach the square in the ith row and jth column
with exactly k value collected so far.
dp[i-1][j][k-mat[i][j]] or
dp[i][j-1][k-mat[i][j]] or
dp[i-1][j-1][k-mat[i][j]]
179
Chapter 23. Check if possible to cross the matrix with given power
if (k == grid[i][j])
dp[i][j][k] = true;
}
// For first cell of each row
else if (i == 0) {
dp[i][j][k] = (dp[i][j][k] ||
dp[i][j - 1][k - grid[i][j]]);
}
// For first cell of each column
else if (j == 0) {
dp[i][j][k] = (dp[i][j][k] ||
dp[i - 1][j][k - grid[i][j]]);
}
// For rest of the cell
else {
// Down movement.
dp[i][j][k] = (dp[i][j][k] ||
dp[i][j - 1][k - grid[i][j]]);
// Right movement.
dp[i][j][k] = (dp[i][j][k] ||
dp[i - 1][j][k - grid[i][j]]);
// Diagonal movement.
dp[i][j][k] = (dp[i][j][k] ||
dp[i - 1][j - 1][k - grid[i][j]]);
}
}
}
}
// Finding maximum k.
int ans = 0;
for (ans = k; ans >= 0; ans--)
if (dp[n - 1][m - 1][ans])
break;
return ans;
}
// Driver Code
int main()
{
int n = 3, m = 4, p = 9;
180
Chapter 23. Check if possible to cross the matrix with given power
int grid[R][C] = {
{ 2, 3, 4, 1 },
{ 6, 5, 5, 3 },
{ 5, 2, 3, 4 }
};
cout << maximumValue(n, m, p, grid) << endl;
return 0;
}
Java
181
Chapter 23. Check if possible to cross the matrix with given power
182
Chapter 23. Check if possible to cross the matrix with given power
{ 5, 2, 3, 4 }};
System.out.println(maximumValue(n, m, p, grid));
}
}
// This code is contributed by Anant Agarwal.
C#
// C# program to find if it
// is possible to cross the matrix
// with given power
using System;
class GFG {
static int N = 105;
// static int R = 3;
// static int C = 4;
static int maximumValue(int n, int m, int p,
int[, ] grid)
{
bool[,, ] dp = new bool[N, N, N];
int i, j, k;
// Initializing array dp with false value.
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
for (k = 0; k < N; k++)
dp[i, j, k] = false;
}
}
// For each value of dp[i][j][k]
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
for (k = grid[i, j]; k <= p; k++) {
// For first cell and for
// each value of k
if (i == 0 && j == 0) {
if (k == grid[i, j])
dp[i, j, k] = true;
}
// For first cell of each row
183
Chapter 23. Check if possible to cross the matrix with given power
else if (i == 0) {
dp[i, j, k] = (dp[i, j, k] ||
dp[i, j - 1, k - grid[i, j]]);
}
// For first cell of each column
else if (j == 0) {
dp[i, j, k] = (dp[i, j, k] ||
dp[i - 1, j, k - grid[i, j]]);
}
// For rest of the cell
else {
// Down movement.
dp[i, j, k] = (dp[i, j, k] ||
dp[i, j - 1, k - grid[i, j]]);
// Right movement.
dp[i, j, k] = (dp[i, j, k] ||
dp[i - 1, j, k - grid[i, j]]);
// Diagonal movement.
dp[i, j, k] = (dp[i, j, k] ||
dp[i - 1, j - 1, k - grid[i, j]]);
}
}
}
}
k = p;
// Finding maximum k.
int ans = 0;
for (ans = k; ans >= 0; ans--)
if (dp[n - 1, m - 1, ans])
break;
return ans;
}
// Driver code
public static void Main()
{
int n = 3, m = 4, p = 9;
int[, ] grid = { { 2, 3, 4, 1 },
{ 6, 5, 5, 3 },
{ 5, 2, 3, 4 } };
184
Chapter 23. Check if possible to cross the matrix with given power
Console.WriteLine(maximumValue(n, m, p, grid));
}
}
// This code is contributed by vt_m.
Output:
-1
Source
https://www.geeksforgeeks.org/check-possible-cross-matrix-given-power/
185
Chapter 24
• (i-j, j)
• (i, i-j)
• (i+j, j)
• (i, i+j)
186
Chapter 24. Check if possible to move from given coordinate to desired coordinate
If we take a closer look at the problem, we can notice that the moves are similar steps of
Euclidean algorithm for finding GCD. So, it is only possible to reach coordinate (a, b) from
(x, y) if GCD of x, y is equal to GCD of a, b. Otherwise, it is not possible.
Let GCD of (x, y) be gcd. From (x, y), we can reach (gcd, gcd) and from this point, we can
reach to (a, b) if and only if GCD of ‘a’ and ‘b’ is also gcd.
Below is the implementation of this approach:
C/C++
187
Chapter 24. Check if possible to move from given coordinate to desired coordinate
Java
188
Chapter 24. Check if possible to move from given coordinate to desired coordinate
Python
C#
189
Chapter 24. Check if possible to move from given coordinate to desired coordinate
if (i > j)
return gcd(i - j, j);
return gcd(i, j - i);
}
// Returns true if it is possble
// to go to (a, b) from (x, y)
static bool ispossible(int x, int y,
int a, int b)
{
// Find absolute values of all as
// sign doesn't matter.
x = Math.Abs(x);
y = Math.Abs(y);
a = Math.Abs(a);
b = Math.Abs(b);
// If gcd is equal then it is possible
// to reach. Else not possible.
return (gcd(x, y) == gcd(a, b));
}
// Driver code
public static void Main()
{
// Converting coordinate
// into positive integer
int x = 35, y = 15;
int a = 20, b = 25;
if (ispossible(x, y, a, b))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to check if it
// is possible to reach
// (a, b) from (x, y).
190
Chapter 24. Check if possible to move from given coordinate to desired coordinate
// Returns GCD of i and j
function gcd($i, $j)
{
if ($i == $j)
return $i;
if ($i > $j)
return gcd($i - $j, $j);
return gcd($i, $j - $i);
}
// Returns true if it is
// possble to go to (a, b)
// from (x, y)
function ispossible($x, $y, $a, $b)
{
// Find absolute values
// of all as sign doesn't
// matter.
$x = abs($x);
$y = abs($y);
$a = abs($a);
$b = abs($b);
// If gcd is equal then
// it is possible to reach.
// Else not possible.
return (gcd($x, $y) == gcd($a, $b));
}
// Driver Code
{
// Converting coordinate
// into positive integer
$x = 35; $y = 15;
$a = 20; $b = 25;
if (ispossible($x, $y, $a, $b))
echo( "Yes");
else
echo( "No");
return 0;
}
// This code is contributed by nitin mittal.
?>
191
Chapter 24. Check if possible to move from given coordinate to desired coordinate
Output:
Yes
Source
https://www.geeksforgeeks.org/check-possible-move-given-coordinate-desired-coordinate/
192
Chapter 25
Check if sums of i-th row and i-th column are same in matrix - GeeksforGeeks
Given a matrix mat[][], we have to check if the sum of i-th row is equal to the sum of i-th
column or not.
Examples:
Input : 1 2 3 4
9 5 3 1
0 3 5 6
0 4 5 6
Output : Yes
Sums of 1st row = 10 and 1st column
are same, i.e., 10
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
193
Chapter 25. Check if sums of i-th row and i-th column are same in matrix
Java
194
Chapter 25. Check if sums of i-th row and i-th column are same in matrix
sum1 += a[i][j];
sum2 += a[j][i];
}
if (sum1 == sum2)
return true;
}
return false;
}
// Driver code
public static void main(String args[])
{
int n = 4; // number of rows
int m = 4; // number of columns
int M[][] = { { 1, 2, 3, 4 },
{ 9, 5, 3, 1 },
{ 0, 3, 5, 6 },
{ 0, 4, 5, 6 } };
if(areSumSame(M, n, m) == true)
System.out.print("1\n");
else
System.out.print("0\n");
}
}
// This code is contributed by Sam007.
Python3
195
Chapter 25. Check if sums of i-th row and i-th column are same in matrix
C#
196
Chapter 25. Check if sums of i-th row and i-th column are same in matrix
return false;
}
// Driver code
public static void Main ()
{
int n = 4; // number of rows
int m = 4; // number of columns
int [,] M = { { 1, 2, 3, 4 },
{ 9, 5, 3, 1 },
{ 0, 3, 5, 6 },
{ 0, 4, 5, 6 } };
if(areSumSame(M, n, m) == true)
Console.Write("1\n");
else
Console.Write("0\n");
}
}
// This code is contributed by Sam007.
Output:
Improved By : Sam007
Source
https://www.geeksforgeeks.org/check-sums-th-row-th-column-matrix/
197
Chapter 26
Input : N = 2
C = {
{ 1, 0 },
{ 0, 1 }
}
Output : Yes
Input : N = 2
C = {
{ 0, 0 },
{ 0, 0 }
}
Output : No
198
Chapter 26. Check if the given chessboard is valid or not
Observe, on a chess board, every adjacent pair of cells is painted in different color.
So, for each cell (i, j), check whether the adjacent cells i.e
(i + 1, j), (i -1, j), (i, j + 1), (i, j – 1) is painted with different color than (i, j) or not.
Psedocode:
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX 2
// Check if the given chess board is valid or not.
bool isValid(int c[][MAX], int n)
{
int X[] = { 0, -1, 0, 1 };
int Y[] = { 1, 0, -1, 0 };
bool isValid = true;
199
Chapter 26. Check if the given chessboard is valid or not
Python 3
200
Chapter 26. Check if the given chessboard is valid or not
for i in range(n) :
for j in range(n) :
# for each adjacent cells
for k in range(n) :
newX = i + X[k]
newY = j + Y[k]
# checking if they have
# different color
if (newX < n and newY < n and
newX >= 0 and newY >= 0 and
c[newX][newY] == c[i][j]) :
isValid = false
return isValid
# Driver Code
if __name__ == "__main__" :
n = 2
c = [ [1, 0],
[0, 1] ]
if isValid(c, n) :
print("Yes")
else :
print("No")
# This code is contributed
# by ANKITRAI1
Output :
Yes
Improved By : ANKITRAI1
Source
https://www.geeksforgeeks.org/check-if-the-given-chessboard-is-valid-or-not/
201
Chapter 27
A*At = I
Examples :
Input: 1 0 0
0 1 0
0 0 1
Output: Yes
Given Matrix is an orthogonal matrix. When
we multiply it with its transpose, we get
identity matrix.
Input: 1 2 3
4 5 6
7 8 9
Output: No
Given Matrix Is Not An Orthogonal Matrix
Simple Solution : The idea is simple, we first find transpose of matrix. Then we multiply
the transpose with given matrix. Finally we check if the matrix obtained is identity or not.
C++
202
Chapter 27. Check whether a given matrix is orthogonal or not
203
Chapter 27. Check whether a given matrix is orthogonal or not
return false;
}
}
return true;
}
// Driver Code
int main()
{
int a[][MAX] = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
if (isOrthogonal(a, 3, 3))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
204
Chapter 27. Check whether a given matrix is orthogonal or not
{
int sum = 0;
for (int k = 0; k < n; k++)
{
// Since we are multiplying
// transpose of itself. We use
sum = sum + (a[i][k] * a[j][k]);
}
prod[i][j] = sum;
}
}
// Check if product is
// identity matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j && prod[i][j] != 0)
return false;
if (i == j && prod[i][j] != 1)
return false;
}
}
return true;
}
// Driver code
static public void main (String[] args)
{
int [][]a = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
if (isOrthogonal(a, 3, 3))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by anuj_67.
Python3
205
Chapter 27. Check whether a given matrix is orthogonal or not
# whether a matrix is
# orthogonal or not
def isOrthogonal(a, m, n) :
if (m != n) :
return False
trans = [[0 for x in range(n)]
for y in range(n)]
# Find transpose
for i in range(0, n) :
for j in range(0, n) :
trans[i][j] = a[j][i]
prod = [[0 for x in range(n)]
for y in range(n)]
# Find product of a[][]
# and its transpose
for i in range(0, n) :
for j in range(0, n) :
sum = 0
for k in range(0, n) :
# Since we are multiplying
# with transpose of itself.
# We use
sum = sum + (a[i][k] *
a[j][k])
prod[i][j] = sum
# Check if product is
# identity matrix
for i in range(0, n) :
for j in range(0, n) :
if (i != j and prod[i][j] != 0) :
return False
if (i == j and prod[i][j] != 1) :
return False
return True
# Driver Code
a = [[1, 0, 0],
206
Chapter 27. Check whether a given matrix is orthogonal or not
[0, 1, 0],
[0, 0, 1]]
if (isOrthogonal(a, 3, 3)) :
print ("Yes")
else :
print ("No")
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
207
Chapter 27. Check whether a given matrix is orthogonal or not
}
prod[i, j] = sum;
}
}
// Check if product is
// identity matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j && prod[i, j] != 0)
return false;
if (i == j && prod[i, j] != 1)
return false;
}
}
return true;
}
// Driver code
static public void Main ()
{
int [,]a = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
if (isOrthogonal(a, 3, 3))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP code to check whether
// a matrix is orthogonal or not
function isOrthogonal($a,
$m, $n)
{
if ($m != $n)
return false;
208
Chapter 27. Check whether a given matrix is orthogonal or not
// Find transpose
for($i = 0; $i < $n; $i++)
for ($j = 0; $j < $n; $j++)
$trans[$i][$j] = $a[$j][$i];
// Find product of a[][]
// and its transpose
for($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
$sum = 0;
for ($k = 0; $k < $n; $k++)
{
// Since we are multiplying with
// transpose of itself. We use
$sum = $sum + ($a[$i][$k] *
$a[$j][$k]);
}
$prod[$i][$j] = $sum;
}
}
// Check if product is
// identity matrix
for($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
if ($i != $j && $prod[$i][$j] != 0)
return false;
if ($i == $j && $prod[$i][$j] != 1)
return false;
}
}
return true;
}
// Driver Code
$a = array(array(1, 0, 0),
array(0, 1, 0),
array(0, 0, 1));
if (isOrthogonal($a, 3, 3))
209
Chapter 27. Check whether a given matrix is orthogonal or not
echo "Yes";
else
echo "No";
// This code is contributed by ajit.
?>
Output :
Yes
An efficient solution is to combine three traversals into one. Instead of explicitly finding
transpose, we use a[j][k] instead of a[k][j]. Also, instead of explicitly computing product, we
check identity while computing product.
C++
210
Chapter 27. Check whether a given matrix is orthogonal or not
Java
211
Chapter 27. Check whether a given matrix is orthogonal or not
Python3
212
Chapter 27. Check whether a given matrix is orthogonal or not
for j in range(0, n) :
sum = 0
for k in range(0, n) :
# Since we are multiplying
# with transpose of itself.
# We use a[j][k] instead
# of a[k][j]
sum = sum + (a[i][k] *
a[j][k])
if (i == j and sum != 1) :
return False
if (i != j and sum != 0) :
return False
return True
# Driver Code
a = [[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
if (isOrthogonal(a, 3, 3)) :
print ("Yes")
else :
print ("No")
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
213
Chapter 27. Check whether a given matrix is orthogonal or not
int sum = 0;
for (int k = 0; k < n; k++) {
// Since we are multiplying with
// transpose of itself. We use
// a[j][k] instead of a[k][j]
sum = sum + (a[i,k] * a[j,k]);
}
if (i == j && sum != 1)
return false;
if (i != j && sum != 0)
return false;
}
}
return true;
}
// Driver code
public static void Main ()
{
int [,]a = {{1, 0, 0},
{0, 1, 0},
{0, 0, 1}};
if (isOrthogonal(a, 3, 3))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP code to check whether
// a matrix is orthogonal or not
//$MAX = 100;
function isOrthogonal($a, $m, $n)
{
214
Chapter 27. Check whether a given matrix is orthogonal or not
if ($m != $n)
return false;
// Multiply A*A^t
for ( $i = 0; $i < $n; $i++)
{
for ( $j = 0; $j < $n; $j++)
{
$sum = 0;
for ( $k = 0; $k < $n; $k++)
{
// Since we are multiplying
// with transpose of itself.
// We use a[j][k] instead
// of a[k][j]
$sum = $sum + ($a[$i][$k] *
$a[$j][$k]);
}
if ($i == $j and $sum != 1)
return false;
if ($i != $j and $sum != 0)
return false;
}
}
return true;
}
// Driver Code
$a = array(array(1, 0, 0),
array(0, 1, 0),
array(0, 0, 1));
if (isOrthogonal($a, 3, 3))
echo "Yes";
else
echo "No";
// This code is contributed by anuj_67.
?>
Output :
Yes
215
Chapter 27. Check whether a given matrix is orthogonal or not
Source
https://www.geeksforgeeks.org/check-whether-given-matrix-orthogonal-not/
216
Chapter 28
Check whether row or column swaps produce maximum size binary sub-matrix with all 1s -
GeeksforGeeks
Given a binary matrix, the task is to find whether row swaps or column swaps give maximum
size sub-matrix with all 1’s. In a row swap, we are allowed to swap any two rows. In a
column swap we are allowed to swap any two columns. Output “Row Swap” or “Column
Swap” and the maximum size.
Examples:
Input : 1 1 1
1 0 1
Output : Column Swap
4
By swapping column 1 and column 2(0-based indexing),
index (0, 0) to (1, 1) makes the largest binary
sub-matrix.
Input : 0 0 0
1 1 0
1 1 0
0 0 0
1 1 0
Output : Row Swap
6
Input : 1 1 0
217
Chapter 28. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
0 0 0
0 0 0
1 1 0
1 1 0
0 0 0
1 1 0
Output : Row Swap
8
The idea is to find both row swap and column swap maximum size binary submatrix and
compare.
To find the maximum sized binary sub-matrix with row swaps allowed, make a 2-D array,
say dp[i][j]. Each value of dp[i][j] contains the number of consecutive 1s on right side of (i,j)
in i-th row. Now, store each column in the 1-D temporary array one by one, say b[] and
sort, and find maximum b[i] * (n – i), since b[i] is indicating the sub-matrix width and (n –
i) is sub-matrix height.
Similarly, to find the maximum size binary sub-matrix with column swap allowed, find
dp[i][j], where each value contains the number of consecutive 1 below the (i, j) in j-th
column. Similarly, store each row in the 1-D temporary array one by one, say b[] and sort.
Find maximum b[i] * (m – i), since b[i] is indicating the submatrix height and (n – i) is
submatrix width.
Below is C++ implementation of this approach:
218
Chapter 28. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
else
ryt[i][j] = ryt[i][j + 1] + 1;
}
}
// Travesing the 2d matrix from bottom-left.
for (int i = R - 1; i >= 0; i--)
{
for (int j = 0; j < C; ++j)
{
// If (i,j) contain 0, do nothing
if (mat[i][j] == 0)
dwn[i][j] = 0;
// Counting consecutive 1 down to (i,j).
else
dwn[i][j] = dwn[i + 1][j] + 1;
}
}
}
// Return maximum size submatrix with row swap allowed.
int solveRowSwap(int ryt[R + 2][C + 2])
{
int b[R] = { 0 }, ans = 0;
for (int j=0; j<C; j++)
{
// Copying the column
for (int i=0; i<R; i++)
b[i] = ryt[i][j];
// Sort the copied array
sort(b, b + R);
// Find maximum submatrix size.
for (int i = 0; i < R; ++i)
ans = max(ans, b[i] * (R - i));
}
return ans;
}
// Return maximum size submatrix with column
// swap allowed.
int solveColumnSwap(int dwn[R + 2][C + 2])
{
219
Chapter 28. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
220
Chapter 28. Check whether row or column swaps produce maximum size binary sub-matrix
with all 1s
Output:
Row Swap
6
Source
https://www.geeksforgeeks.org/check-whether-row-column-swap-produces-maximum-size-binary-sub-matrix-1s/
221
Chapter 29
Cholesky Decomposition :
Matrix Decomposition
222
Chapter 29. Cholesky Decomposition : Matrix Decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique
lower triangular matrix L and its transpose: A = L LT
The following formulas are obtained by solving above lower triangular matrix and its trans-
pose. These are the basis of Cholesky Decomposition Algorithm :
Example :
Input :
Output :
C++
223
Chapter 29. Cholesky Decomposition : Matrix Decomposition
224
Chapter 29. Cholesky Decomposition : Matrix Decomposition
int n = 3;
int matrix[][MAX] = { { 4, 12, -16 },
{ 12, 37, -43 },
{ -16, -43, 98 } };
Cholesky_Decomposition(matrix, n);
return 0;
}
PHP
<?php
// PHP program to decompose
// a matrix using Cholesky
// Decomposition
$MAX = 100;
function Cholesky_Decomposition($matrix, $n)
{
$lower;
for ($i = 0; $i <= $n; $i++)
for ($j = 0; $j <= $n; $j++)
$lower[$i][$j] = 0;
// Decomposing a matrix
// into Lower Triangular
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j <= $i; $j++)
{
$sum = 0;
// summation for diagnols
if ($j == $i)
{
for ($k = 0; $k < $j; $k++)
$sum += pow($lower[$j][$k], 2);
$lower[$j][$j] = sqrt($matrix[$j][$j] -
$sum);
}
else
{
// Evaluating L(i, j)
// using L(j, j)
for ($k = 0; $k < $j; $k++)
$sum += ($lower[$i][$k] *
$lower[$j][$k]);
$lower[$i][$j] = ($matrix[$i][$j] - $sum) /
$lower[$j][$j];
225
Chapter 29. Cholesky Decomposition : Matrix Decomposition
}
}
}
// Displaying Lower Triangular
// and its Transpose
echo " Lower Triangular" .
str_pad("Transpose", 30, " ",
STR_PAD_BOTH) . "\n";
for ($i = 0; $i < $n; $i++)
{
// Lower Triangular
for ($j = 0; $j < $n; $j++)
echo str_pad($lower[$i][$j], 6,
" ", STR_PAD_BOTH)."\t";
echo "\t";
// Transpose of
// Lower Triangular
for ($j = 0; $j < $n; $j++)
echo str_pad($lower[$j][$i], 6,
" ", STR_PAD_BOTH)."\t";
echo "\n";
}
}
// Driver Code
$n = 3;
$matrix = array(array(4, 12, -16),
array(12, 37, -43),
array(-16, -43, 98));
Cholesky_Decomposition($matrix, $n);
// This code is contributed by vt_m.
?>
C#
// C# program to decompose
// a matrix using Cholesky
// Decomposition
using System;
class GFG
{
//static int MAX = 100;
226
Chapter 29. Cholesky Decomposition : Matrix Decomposition
227
Chapter 29. Cholesky Decomposition : Matrix Decomposition
Output:
Source
https://www.geeksforgeeks.org/cholesky-decomposition-matrix-decomposition/
228
Chapter 30
Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way) - GeeksforGeeks
Given two values m and n, fill a matrix of size ‘m*n’ in spiral (or circular) fashion (clockwise)
with natural numbers from 1 to m*n.
Examples:
Input : m = 4, n = 4
Output : 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Input : m = 3, n = 4
Output : 1 2 3 4
10 11 12 5
9 8 7 6
The idea is based on Print a given matrix in spiral form. We create a matrix of size m * n
and traverse it in spiral fashion. While traversing, we keep track of a variable “val” to fill
next value, we increment “val” one by one and put its values in the matrix.
229
Chapter 30. Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
const int MAX = 100;
// Fills a[m][n] with values from 1 to m*n in
// spiral fashion.
void spiralFill(int m, int n, int a[][MAX])
{
// Initialize value to be filled in matrix
int val = 1;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index */
int k = 0, l = 0;
while (k < m && l < n)
{
/* Print the first row from the remaining
rows */
for (int i = l; i < n; ++i)
a[k][i] = val++;
k++;
/* Print the last column from the remaining
columns */
for (int i = k; i < m; ++i)
a[i][n-1] = val++;
n--;
/* Print the last row from the remaining
rows */
if (k < m)
{
for (int i = n-1; i >= l; --i)
a[m-1][i] = val++;
m--;
}
/* Print the first column from the remaining
columns */
if (l < n)
{
for (int i = m-1; i >= k; --i)
a[i][l] = val++;
l++;
}
}
230
Chapter 30. Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
}
/* Driver program to test above functions */
int main()
{
int m = 4, n = 4;
int a[MAX][MAX];
spiralFill(m, n, a);
for (int i=0; i<m; i++)
{
for (int j=0; j<n; j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Output:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Source
https://www.geeksforgeeks.org/circular-matrix-construct-a-matrix-with-numbers-1-to-mn-in-spiral-way/
231
Chapter 31
1. Move one step ahead, i.e., cell (i, j-1) and direction remains left.
2. Move one step down and face right, i.e., cell (i+1, j) and direction becomes right.
Final position can be anywhere and final direction can also be anything. The target is to
collect maximum coins.
232
Chapter 31. Collect maximum coins before hitting a dead end
Example:
We strongly recommend you to minimize your browser and try this yourself
first.
The above problem can be recursively defined as below:
// Initialize result
If (arr[i][j] == 'C')
result = 1;
Else
result = 0;
If (d == 0) // Left direction
return result + max(maxCoins(i+1, j, 1), // Down
maxCoins(i, j-1, 0)); // Ahead in left
If (d == 1) // Right direction
233
Chapter 31. Collect maximum coins before hitting a dead end
234
Chapter 31. Collect maximum coins before hitting a dead end
};
// As per the question initial cell is (0, 0) and direction is
// right
cout << "Maximum number of collected coins is "
<< maxCoinsRec(arr, 0, 0, 1);
return 0;
}
Output:
The time complexity of above solution recursive is exponential. We can solve this problem
in Polynomial Time using Dynamic Programming. The idea is to use a 3 dimensional table
dp[R][C][k] where R is number of rows, C is number of columns and d is direction. Below
is Dynamic Programming based C++ implementation.
235
Chapter 31. Collect maximum coins before hitting a dead end
// Check if this cell contains the coin 'C' or if its 'E'.
dp[i][j][dir] = (arr[i][j] == 'C')? 1: 0;
// Get the maximum of two cases when you are facing right
// in this cell
if (dir == 1) // Direction is right
dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 0, dp), // Down
maxCoinsUtil(arr, i, j+1, 1, dp)); // Ahead in rught
// Get the maximum of two cases when you are facing left
// in this cell
if (dir == 0) // Direction is left
dp[i][j][dir] += max(maxCoinsUtil(arr, i+1, j, 1, dp), // Down
maxCoinsUtil(arr, i, j-1, 0, dp)); // Ahead in left
// return the answer
return dp[i][j][dir];
}
// This function mainly creates a lookup table and calls
// maxCoinsUtil()
int maxCoins(char arr[R][C])
{
// Create lookup table and initialize all values as -1
int dp[R][C][2];
memset(dp, -1, sizeof dp);
// As per the question initial cell is (0, 0) and direction
// is right
return maxCoinsUtil(arr, 0, 0, 1, dp);
}
// Driver program to test above function
int main()
{
char arr[R][C] = { {'E', 'C', 'C', 'C', 'C'},
{'C', '#', 'C', '#', 'E'},
{'#', 'C', 'C', '#', 'C'},
{'C', 'E', 'E', 'C', 'E'},
{'C', 'E', '#', 'C', 'E'}
};
cout << "Maximum number of collected coins is "
<< maxCoins(arr);
return 0;
236
Chapter 31. Collect maximum coins before hitting a dead end
Output:
Time Complexity of above solution is O(R x C x d). Since d is 2, time complexity can be
written as O(R x C).
Thanks to Gaurav Ahirwar for suggesting above solution.
Source
https://www.geeksforgeeks.org/collect-maximum-coins-before-hitting-a-dead-end/
237
Chapter 32
Input :
int arr[R][C] = {{3, 6, 8, 2},
{5, 2, 4, 3},
{1, 1, 20, 10},
{1, 1, 20, 10},
{1, 1, 20, 10},
};
Output: 73
Explanation :
238
Chapter 32. Collect maximum points in a grid using two traversals
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to do both traversals concurrently. We start first from (0, 0) and second traversal
from (0, C-1) simultaneously. The important thing to note is, at any particular step both
traversals will be in same row as in all possible three moves, row number is increased. Let
(x1, y1) and (x2, y2) denote current positions of first and second traversals respectively.
Thus at any time x1 will be equal to x2 as both of them move forward but variation is
possible along y. Since variation in y could occur in 3 ways no change (y), go left (y – 1),
go right (y + 1). So in total 9 combinations among y1, y2 are possible. The 9 cases as
mentioned below after base cases.
// If both traversals are at same cell, then we count the value of cell
// only once.
If y1 and y2 are same
result = arr[x][y1]
Else
result = arr[x][y1] + arr[x][y2]
The above recursive solution has many subproblems that are solved again and again. There-
fore, we can use Dynamic Programming to solve the above problem more efficiently. Below
is memoization (Memoization is alternative to table based iterative solution in Dynamic Pro-
239
Chapter 32. Collect maximum points in a grid using two traversals
240
Chapter 32. Collect maximum points in a grid using two traversals
Output:
Maximum collection is 73
Source
https://www.geeksforgeeks.org/collect-maximum-points-in-a-grid-using-two-traversals/
241
Chapter 33
Input:
mat[4][5] = {{1, 2, 1, 4, 8},
{3, 7, 8, 5, 1},
{8, 7, 7, 3, 1},
{8, 1, 2, 7, 9},
};
Output:
1 8 or 8 1
8 and 1 are present in all rows.
A simple solution is to consider every element and check if it is present in all rows. If
present, then print it.
A better solution is to sort all rows in the matrix and use similar approach as discussed
here. Sorting will take O(mnlogn) time and finding common elements will take O(mn) time.
So overall time complexity of this solution is O(mnlogn)
Can we do better than O(mnlogn)?
The idea is to use maps. We initially insert all elements of the first row in an map. For
every other element in remaining rows, we check if it is present in the map. If it is present
242
Chapter 33. Common elements in all rows of a given matrix
in the map and is not duplicated in current row, we increment count of the element in map
by 1, else we ignore the element. If the currently traversed row is the last row, we print the
element if it has appeared m-1 times before.
Below is C++ implementation of the idea.
243
Chapter 33. Common elements in all rows of a given matrix
int mat[M][N] =
{
{1, 2, 1, 4, 8},
{3, 7, 8, 5, 1},
{8, 7, 7, 3, 1},
{8, 1, 2, 7, 9},
};
printCommonElements(mat);
return 0;
}
Output:
8 1
The time complexity of this solution is O(m * n) and we are doing only one traversal of the
matrix.
Source
https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/
244
Chapter 34
mat[i][j] = 1 if i is ancestor of j
mat[i][j] = 0, otherwise
Examples:
245
Chapter 34. Construct Ancestor Matrix from a Given Binary Tree
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 0
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to traverse the tree. While traversing, keep track of ancestors in an array. When
we visit a node, we add it to ancestor array and consider corresponding row in adjacency
matrix. We mark all ancestors in its row as 1. Once a node and all its children are processed,
we remove the node from ancestor array.
Below is C++ implementation of above idea.
246
Chapter 34. Construct Ancestor Matrix from a Given Binary Tree
247
Chapter 34. Construct Ancestor Matrix from a Given Binary Tree
root->right = newnode(2);
root->left->left = newnode(0);
root->left->right = newnode(4);
root->right->left = newnode(3);
ancestorMatrix(root);
return 0;
}
Output:
0 0 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 0
Source
https://www.geeksforgeeks.org/construct-ancestor-matrix-from-a-given-binary-tree/
248
Chapter 35
Input : 2D matrix
1 2 3
4 5 6
7 8 9
Output :
1 -> 2 -> 3 -> NULL
| | |
v v v
4 -> 5 -> 6 -> NULL
| | |
v v v
7 -> 8 -> 9 -> NULL
| | |
v v v
NULL NULL NULL
C++
249
Chapter 35. Construct a linked list from 2D matrix
250
Chapter 35. Construct a linked list from 2D matrix
}
cout << "\n";
Dp = Dp->down;
}
}
// driver program
int main()
{
// 2D matrix
int arr[][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
int m = 3, n = 3;
Node* head = construct(arr, 0, 0, m, n);
display(head);
return 0;
}
Java
251
Chapter 35. Construct a linked list from 2D matrix
temp.data = arr[i][j];
temp.right = construct(arr, i, j + 1, m, n);
temp.down = construct(arr, i + 1, j, m, n);
return temp;
}
// utility function for displaying
// linked list data
static void display(Node head) {
// pointer to move right
Node Rp;
// pointer to move down
Node Dp = head;
// loop till node->down is not NULL
while (Dp != null) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp != null) {
System.out.print(Rp.data + " ");
Rp = Rp.right;
}
System.out.println();
Dp = Dp.down;
}
}
// driver program
public static void main(String args[]) {
// 2D matrix
int arr[][] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int m = 3, n = 3;
Node head = construct(arr, 0, 0, m, n);
display(head);
}
}
// This code is contributed by Sumit Ghosh
Output:
252
Chapter 35. Construct a linked list from 2D matrix
1 2 3
4 5 6
7 8 9
Source
https://www.geeksforgeeks.org/construct-linked-list-2d-matrix/
253
Chapter 36
Input: [1 2 3
4 5 6
7 8 9]
Output:
1 -> 2 -> 3 -> NULL
| | |
v v v
4 -> 5 -> 6 -> NULL
| | |
v v v
7 -> 8 -> 9 -> NULL
| | |
v v v
NULL NULL NULL
A recursive solution for this problem has been already discussed in this post. Below is an
iterative approach for the problem:
• The idea is to create m linked lists (m = number of rows) whose each node stores its
right node. The head pointers of each m linked lists are stored in an array of nodes.
254
Chapter 36. Construct a linked list from 2D matrix (Iterative Approach)
• Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each
node of ith list to its corresponding node of (i+1)th list.
255
Chapter 36. Construct a linked list from 2D matrix (Iterative Approach)
256
Chapter 36. Construct a linked list from 2D matrix (Iterative Approach)
righttemp->right = newptr;
righttemp = newptr;
}
}
// Then, for every ith and (i+1)th list,
// we set the down pointers of
// every node of ith list
// with its corresponding
// node of (i+1)th list
for (int i = 0; i < m - 1; i++) {
node *temp1 = head[i], *temp2 = head[i + 1];
while (temp1 && temp2) {
temp1->down = temp2;
temp1 = temp1->right;
temp2 = temp2->right;
}
}
// return the mainhead pointer of the linked list
return mainhead;
}
// Driver program to test the above function
int main()
{
int m, n; // m = rows and n = columns
m = 3, n = 3;
// 2D matrix
int mat[][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
node* head = constructLinkedMatrix(mat, m, n);
display(head);
return 0;
}
Output:
1 2 3
4 5 6
257
Chapter 36. Construct a linked list from 2D matrix (Iterative Approach)
7 8 9
Source
https://www.geeksforgeeks.org/construct-a-linked-list-from-2d-matrix-iterative-approach/
258
Chapter 37
Example :
Input : n = 1
Output : 1
Input : n = 3
Output: 3 2 1
1 3 2
2 1 3
Input : n = 5
Output : 5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5
The idea is to first decide positions of 1s. Once possible arrangement of 1s for n = 5 is,
259
Chapter 37. Construct a unique matrix n x n for an input n
_ _ _ _ 1
1 _ _ _ _
_ _ _ 1 _
_ 1 _ _ _
_ _ 1 _ _
Once we have decided 1s, task of filling remaining items is simple. We fill remaining entries
column by column. For every 1, we traverse its column and fill all entries below it with 2,
3,…p and fill all entries above it with p+1, .. n. We get following.
5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5
To decide initial positions of 1s, we traverse all rows and keep track of two column numbers
“left” and “right”.
1) “right” starts with n-1 and keep decrementing after every alternate row.
2) “left” starts with 0 and keep incrementing after every alternate row.
Below are implementations of above idea.
C++
260
Chapter 37. Construct a unique matrix n x n for an input n
261
Chapter 37. Construct a unique matrix n x n for an input n
}
// Driver code
int main()
{
int n = 5;
// Passing n to constructMatrix function
constructMatrix(n);
// Printing the desired unique matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
printf("%d ",mat[i][j]);
printf ("\n");
}
return 0;
}
Java
262
Chapter 37. Construct a unique matrix n x n for an input n
}
// Fills entries in mat[][]
// with the given set of rules
static void constructMatrix(int n)
{
// Alternatively fill 1s starting from
// rightmost and leftmost columns. For
// example for n = 3, we get { {_ _ 1},
// {1 _ _} {_ 1 _}}
int right = n - 1, left = 0;
for (int i = 0; i < n; i++)
{
// If i is even, then fill
// next column from right
if (i % 2 == 0)
{
mat[i][right] = 1;
// After filling 1, fill remaining
// entries of column "right"
fillRemaining(i, right, n);
// Move right one column back
right--;
}
// Fill next column from left
else
{
mat[i][left] = 1;
// After filling 1, fill remaining
// entries of column "left"
fillRemaining(i, left, n);
// Move left one column forward
left++;
}
}
}
// Driver Code
public static void main(String args[])
{
int n = 5;
// Passing n to constructMatrix function
263
Chapter 37. Construct a unique matrix n x n for an input n
constructMatrix(n);
// Printing the desired unique matrix
for (int i = 0; i < n; i++)
{
for (int j = 0 ; j < n; j++)
System.out.print(mat[i][j]+" ");
System.out.println();
}
}
}
// This code is contributed by Sumit Ghosh
C#
// C# program to construct an n x n
// matrix such that every row and
// every column has distinct values.
using System;
class GFG
{
static int MAX = 100;
static int [,]mat = new int[MAX, MAX];
// Fills non-one entries in column j
// Given that there is a "1" at
// position mat[i][j], this function
// fills other entries of column j.
static void fillRemaining(int i, int j, int n)
{
// Initialize value to be filled
int x = 2;
// Fill all values below i as 2, 3, ...p
for (int k = i + 1; k < n; k++)
mat[k, j] = x++;
// Fill all values above i
// as p + 1, p + 2, .. n
for (int k = 0; k < i; k++)
mat[k, j] = x++;
}
// Fills entries in mat[][]
// with the given set of rules
264
Chapter 37. Construct a unique matrix n x n for an input n
265
Chapter 37. Construct a unique matrix n x n for an input n
{
for (int j = 0 ; j < n; j++)
Console.Write(mat[i, j]+" ");
Console.WriteLine();
}
}
}
// This code is contributed by nitin mittal
Output :
5 3 2 4 1
1 4 3 5 2
2 5 4 1 3
3 1 5 2 4
4 2 1 3 5
Source
https://www.geeksforgeeks.org/construct-unique-matrix-n-x-n-input-n/
266
Chapter 38
mat[i][j] = 1 if i is ancestor of j
mat[i][j] = 0, otherwise
Construct a Binary Tree from given ancestor matrix where all its values of nodes are from
0 to n-1.
1. It may be assumed that the input provided the program is valid and tree can be
constructed out of it.
2. Many Binary trees can be constructed from one input. The program will construct
any one of them.
Examples:
Input: 0 1 1
0 0 0
0 0 0
Output: Root of one of the below trees.
0 0
/ \ OR / \
1 2 2 1
Input: 0 0 0 0 0 0
267
Chapter 38. Construct tree from ancestor matrix
1 0 0 0 1 0
0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 0
Output: Root of one of the below trees.
5 5 5
/ \ / \ / \
1 2 OR 2 1 OR 1 2 OR ....
/ \ / / / \ / \ /
0 4 3 3 0 4 4 0 3
There are different possible outputs because ancestor
matrix doesn't store that which child is left and which
is right.
268
Chapter 38. Construct tree from ancestor matrix
269
Chapter 38. Construct tree from ancestor matrix
node[it->second] = newNode(it->second);
// To store last processed node. This node will be
// root after loop terminates
root = node[it->second];
// if non-leaf node
if (it->first != 0)
{
// traverse row 'it->second' in the matrix
for (int i = 0; i < N; i++)
{
// if parent is not set and ancestor exits
if (!parent[i] && mat[it->second][i])
{
// check for unoccupied left/right node
// and set parent of node i
if (!node[it->second]->left)
node[it->second]->left = node[i];
else
node[it->second]->right = node[i];
parent[i] = 1;
}
}
}
}
return root;
}
/* Given a binary tree, print its nodes in inorder */
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
// Driver program
int main()
{
int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 0 },
{ 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
270
Chapter 38. Construct tree from ancestor matrix
{ 1, 1, 1, 1, 1, 0 }
};
Node* root = ancestorTree(mat);
cout << "Inorder traversal of tree is \n";
printInorder(root);
return 0;
}
Output:
Note that we can also use an array of vectors in place of multimap. We have used multimap
for simplicity. Array of vectors would improve performance as inserting and accessing ele-
ments would take O(1) time.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/construct-tree-from-ancestor-matrix/
271
Chapter 39
The “game” is a zero-player game, meaning that its evolution is determined by its initial
state, requiring no further input. One interacts with the Game of Life by creating an initial
configuration and observing how it evolves, or, for advanced “players”, by creating patterns
with particular properties.
How the game works
1. If a cell is ON and has fewer than two neighbors that are ON, it turns OFF
2. If a cell is ON and has either two or three neighbors that are ON, it remains ON.
3. If a cell is ON and has more than three neighbors that are ON, it turns OFF.
4. If a cell is OFF and has exactly three neighbors that are ON, it turns ON.
272
Chapter 39. Conway’s Game Of Life (Python Implementation)
So since we know how it works, the next thing we need to figure it out that how to make it
work.
Approach
1. numpy
2. matplotlib
3. argparse
273
Chapter 39. Conway’s Game Of Life (Python Implementation)
274
Chapter 39. Conway’s Game Of Life (Python Implementation)
275
Chapter 39. Conway’s Game Of Life (Python Implementation)
N = 100
if args.N and int(args.N) > 8:
N = int(args.N)
# set animation update interval
updateInterval = 50
if args.interval:
updateInterval = int(args.interval)
# declare grid
grid = np.array([])
# check if "glider" demo flag is specified
if args.glider:
grid = np.zeros(N*N).reshape(N, N)
addGlider(1, 1, grid)
elif args.gosper:
grid = np.zeros(N*N).reshape(N, N)
addGosperGliderGun(10, 10, grid)
else: # populate grid with random on/off -
# more off than on
grid = randomGrid(N)
# set up animation
fig, ax = plt.subplots()
img = ax.imshow(grid, interpolation='nearest')
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N, ),
frames = 10,
interval=updateInterval,
save_count=50)
# # of frames?
# set output file
if args.movfile:
ani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
# call main
if __name__ == '__main__':
main()
http://contribute.geeksforgeeks.org/wp-content/uploads/1.mp4
Now lets turn up things a little, let’s see what happens if add updates the animation every
276
Chapter 39. Conway’s Game Of Life (Python Implementation)
500 milliseconds and setting up the dimensions 32X32 and also using the initial glider
pattern.
http://contribute.geeksforgeeks.org/wp-content/uploads/2017-10-27-at-02-28-55.mp4
You can try manipulating this code to create different simulation using this.
Reference Links:
Source
https://www.geeksforgeeks.org/conways-game-life-python-implementation/
277
Chapter 40
We strongly recommend you to minimize your browser and try this yourself
first.
Naive Solution
Here’s a naive, non-optimal solution.
We start from the top left corner and count the number of negative numbers one by one,
from left to right and top to bottom.
With the given example:
278
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Evaluation process
[?, ?, ?, 1]
[?, 2, 3, 4]
[4, 5, 7, 8]
C++
279
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
return 0;
}
// This code is contributed by Niteesh Kumar
Java
280
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Python
C#
281
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
// Follow the path shown
// using arrows above
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if( M[i, j] < 0 )
count += 1;
// no more negative numbers
// in this row
else
break;
}
}
return count;
}
// Driver Code
public static void Main ()
{
int [,]M = { {-3, -2, -1, 1},
{-2, 2, 3, 4},
{4, 5, 7, 8} };
Console.WriteLine(countNegative(M, 3, 4));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation of Naive method
// to count of negative numbers in
// M[n][m]
function countNegative($M, $n, $m)
{
$count = 0;
// Follow the path shown using
// arrows above
for( $i = 0; $i < $n; $i++)
{
for( $j = 0; $j < $m; $j++)
282
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
{
if( $M[$i][$j] < 0 )
$count += 1;
// no more negative numbers
// in this row
else
break;
}
}
return $count;
}
// Driver Code
$M = array(array(-3, -2, -1, 1),
array(-2, 2, 3, 4),
array(4, 5, 7, 8));
echo countNegative($M, 3, 4);
// This code is contributed by anuj_67.
?>
Output :
In this approach we are traversing through the all the elements and therefore, in the worst
case scenario (when all numbers are negative in the matrix), this takes O(n * m) time.
Optimal Solution
Here’s a more efficient solution:
1. We start from the top right corner and find the position of the last negative number
in the first row.
2. Using this information, we find the position of the last negative number in the second
row.
3. We keep repeating this process until we either run out of negative numbers or we get
to the last row.
283
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
C++
284
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
}
// Driver program to test above functions
int main ()
{
int M[3][4] = { {-3, -2, -1, 1},
{-2, 2, 3, 4},
{4, 5, 7, 8} };
cout << countNegative(M, 3, 4);
return 0;
}
// This code is contributed by Niteesh Kumar
Java
285
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Python
286
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
C#
// C# implementation of Efficient
// method to count of negative
// numbers in M[n][m]
using System;
class GFG
{
// Function to count
// negative number
static int countNegative(int [,]M, int n,
int m)
{
// initialize result
int count = 0;
// Start with top right corner
int i = 0;
int j = m - 1;
// Follow the path shown
// using arrows above
while( j >= 0 && i < n )
{
if( M[i, j] < 0 )
{
// j is the index of the
// last negative number
287
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
PHP
<?php
// PHP implementation of Efficient
// method to count of negative numbers
// in M[n][m]
function countNegative( $M, $n, $m)
{
// initialize result
$count = 0;
// Start with top right corner
$i = 0;
$j = $m - 1;
288
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Output :
With this solution, we can now solve this problem in O(n + m) time.
289
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
Source
https://www.geeksforgeeks.org/count-negative-numbers-in-a-column-wise-row-wise-sorted-matrix/
290
Chapter 41
291
Chapter 41. Count all 0s which are blocked by 1s in binary matrix
After that we count all zeros which are left in binary matrix.
Below c++ implementation of above idea.
292
Chapter 41. Count all 0s which are blocked by 1s in binary matrix
if (M[i][Col - 1] == 0)
DFS(i, Col - 1, M);
// count all zeros which are surrounded by 1
int result = 0;
for (int i = 0; i < Row; i++)
for (int j = 0; j < Col; j++)
if (M[i][j] == 0)
result++;
return result;
}
// driver program to test above function
int main()
{
int M[][Col] = { { 1, 1, 1, 0, 1 },
{ 1, 0, 0, 1, 0 },
{ 1, 0, 1, 0, 1 },
{ 0, 1, 1, 1, 1 } };
cout << CountAllZero(M) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-all-0s-which-are-blocked-by-1s-in-binary-matrix/
293
Chapter 42
Count all possible paths from top left to bottom right of a mXn matrix - GeeksforGeeks
The problem is to count all the possible paths from top left to bottom right of a mXn matrix
with the constraints that from each cell you can either move only to right or down
Examples :
Input : m = 2, n = 2;
Output : 2
There are two paths
(0, 0) -> (0, 1) -> (1, 1)
(0, 0) -> (1, 0) -> (1, 1)
Input : m = 2, n = 3;
Output : 3
There are three paths
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2)
We have discussed a solution to print all possible paths, counting all paths is easier. Let
NumberOfPaths(m, n) be the count of paths to reach row number m and column number n
in the matrix, NumberOfPaths(m, n) can be recursively written as following.
C++
#include <iostream>
294
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix
Java
295
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix
Python
Output:
The time complexity of above recursive solution is exponential. There are many overlap-
ping subproblems. We can draw a recursion tree for numberOfPaths(3, 3) and see many
overlapping subproblems. The recursion tree would be similar to Recursion tree for Longest
Common Subsequence problem.
So this problem has both properties (see this and this) of a dynamic programming problem.
296
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix
#include <iostream>
using namespace std;
// Returns count of possible paths to reach cell at
// row number m and column number n from the topmost
// leftmost cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
// Create a 2D table to store results of subproblems
int count[m][n];
// Count of paths to reach any cell in first column is 1
for (int i = 0; i < m; i++)
count[i][0] = 1;
// Count of paths to reach any cell in first column is 1
for (int j = 0; j < n; j++)
count[0][j] = 1;
// Calculate count of paths for other cells in
// bottom-up manner using the recursive solution
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
// By uncommenting the last part the code calculatest he total
// possible paths if the diagonal Movements are allowed
count[i][j] = count[i-1][j] + count[i][j-1]; //+ count[i-1][j-1];
}
return count[m-1][n-1];
}
// Driver program to test above functions
int main()
{
cout << numberOfPaths(3, 3);
return 0;
}
Java
297
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix
Python
298
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix
Output:
299
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix
class GFG
{
// Returns count of possible paths to reach
// cell at row number m and column number n from
// the topmost leftmost cell (cell at 1, 1)
static int numberOfPaths(int m, int n)
{
// Create a 1D array to store results of subproblems
int[] dp = new int[n];
dp[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
// Driver program to test above function
public static void main(String args[])
{
System.out.println(numberOfPaths(3, 3));
}
}
Output:
Source
https://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
300
Chapter 43
Input : m = 4, n = 5
mat[m][n] = 1 2 3 4 5
4 3 1 2 6
8 7 6 5 4
5 7 8 9 10
Output: 3
C++
301
Chapter 43. Count all sorted rows in a matrix
302
Chapter 43. Count all sorted rows in a matrix
Java
303
Chapter 43. Count all sorted rows in a matrix
break;
// Note c > 1 condition is required to make
// sure that a single column row is not counted
// twice (Note that a single column row is sorted
// both in increasing and decreasing order)
if (c > 1 && j == 0)
result++;
}
return result;
}
// Driver code
public static void main(String arg[])
{
int m = 4, n = 5;
int mat[][] = { { 1, 2, 3, 4, 5 },
{ 4, 3, 1, 2, 6 },
{ 8, 7, 6, 5, 4 },
{ 5, 7, 8, 9, 10 } };
System.out.print(sortedCount(mat, m, n));
}
}
// This code is contributed by Anant Agarwal.
C#
304
Chapter 43. Count all sorted rows in a matrix
305
Chapter 43. Count all sorted rows in a matrix
Console.WriteLine(
sortedCount(mat, m, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find
// number of sorted rows
$MAX = 100;
// Function to count all
// sorted rows in a matrix
function sortedCount($mat,
$r, $c)
{
// Initialize result
$result = 0;
// Start from left side of
// matrix to count increasing
// order rows
for ( $i = 0; $i < $r; $i++)
{
// Check if there is any
// pair ofs element that
// are not in increasing order.
$j;
for ($j = 0; $j < $c - 1; $j++)
if ($mat[$i][$j + 1] <= $mat[$i][$j])
break;
// If the loop didn't break
// (All elements of current
// row were in increasing order)
if ($j == $c - 1)
$result++;
}
// Start from right side of
// matrix to count increasing
// order rows ( refrence to left
// these are in decreasing order )
306
Chapter 43. Count all sorted rows in a matrix
Output :
Source
https://www.geeksforgeeks.org/count-sorted-rows-matrix/
307
Chapter 44
Naive Approach: Traverse the matrix using two nested loops and count the elements
smaller than or equal to x. Time Complexity is of O(n^2).
Efficient Approach: As matrix is strictly sorted, use the concept of binary search tech-
nique. First apply the binary search technique on the elements of the first column to find
308
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
the row index number of the largest element smaller than equal to ‘x’. For duplicates get
the last row index no of occurrence of required element ‘x’. Let it be row_no.. If no such
row exists then return 0. Else apply the concept of binary search technique to find the
column index no of the largest element smaller than or equal to ‘x’ in the row represented
by row_no. Let it col_no. Finally return ((row_no) * n) + (col_no + 1). The
concept of binary search technique can be understood by the binary_search function of
this post.
C++
309
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
{
while (l <= h) {
int mid = (l + h) / 2;
// if 'x' is greater than or equal to mat[row][mid],
// then search in mat[row][mid+1...h]
if (mat[row][mid] <= x)
l = mid + 1;
// else search in mat[row][l...mid-1]
else
h = mid - 1;
}
// required column index number
return h;
}
// function to count elements smaller than
// or equal to x in a sorted matrix
int countSmallElements(int mat[SIZE][SIZE],
int n, int x)
{
// to get the row index number of the largest element
// smaller than equal to 'x' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, x);
// if no such row exists
if (row_no == -1)
return 0;
// to get the column index number of the largest element
// smaller than equal to 'x' in mat[row_no][]
int col_no = binarySearchOnCol(mat, 0, n - 1, x, row_no);
// required count of elements
return ((row_no)*n) + (col_no + 1);
}
// Driver program to test above
int main()
{
int mat[SIZE][SIZE] = { { 1, 4, 7, 8 },
{ 10, 10, 12, 14 },
{ 15, 26, 30, 31 },
{ 31, 42, 46, 50 } };
int n = 4;
int x = 31;
310
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
Java
311
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
312
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
// Driver code
public static void main (String[] args) {
int mat[][] = { { 1, 4, 7, 8 },
{ 10, 10, 12, 14 },
{ 15, 26, 30, 31 },
{ 31, 42, 46, 50 } };
int n = 4;
int x = 31;
System.out.println("Count = "
+ countSmallElements(mat, n, x));
}
}
// This code is contributed by Gitanjali.
Python3
# Python implementation to
# count elements smaller than
# or equal to x in a sorted matrix
SIZE = 100
# function returns the row index
# no of largest element
# smaller than equal to 'x' in
# first column of mat[][].
# For duplicates it returns the
# last row index no of
# occurrence of required element
# 'x'. If no such element
# exits then it returns -1.
def binarySearchOnRow(mat, l, h, x):
while l <= h:
mid = (l + h) // 2
# if 'x' is greater than or
# equal to mat[mid][0],
# then search in mat[mid+1...h][0]
if mat[mid][0] <= x:
l = mid + 1
# else search in mat[l...mid-1][0]
else:
h = mid - 1
# required row index number
313
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
return h
# function returns the column
# index no of largest element
# smaller than equal to 'x'
# in mat[row][].
# For duplicates it returns the
# last column index no of
# occurrence of required element 'x'.
def binarySearchOnCol(mat, l, h, x, row):
while l <= h:
mid = (l + h) // 2
# if 'x' is greater than or
# equal to mat[row][mid],
# then search in mat[row][mid+1...h]
if mat[row][mid] <= x:
l = mid + 1
# else search in mat[row][l...mid-1]
else:
h = mid - 1
# required column index number
return h
# function to count elements smaller than
# or equal to x in a sorted matrix
def countSmallElements(mat, n, x):
# to get the row index number
# of the largest element
# smaller than equal to 'x' in mat[][]
row_no = binarySearchOnRow(mat, 0, n - 1, x)
# if no such row exists
if row_no == -1:
return 0
# to get the column index number
# of the largest element
# smaller than equal to 'x' in mat[row_no][]
col_no = binarySearchOnCol(mat, 0,
n - 1, x, row_no)
# required count of elements
return ((row_no)*n) + (col_no + 1)
# Driver program to test above
314
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
mat = [ [ 1, 4, 7, 8 ],
[ 10, 10, 12, 14 ],
[ 15, 26, 30, 31 ],
[ 31, 42, 46, 50 ] ]
n = 4
x = 31
print("Count = " + str(countSmallElements(mat, n, x)))
# This code is contributed by Ansu Kumari.
C#
315
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
}
// function returns the column index
// no of largest element
// smaller than equal to 'x' in
// mat[row][].For duplicates it returns
// the last column index no of
// occurrence of required element 'x'.
static int binarySearchOnCol(int [,]mat, int l,
int h, int x, int row)
{
while (l <= h) {
int mid = (l + h) / 2;
// if 'x' is greater than or
// equal to mat[row][mid], then
// search in mat[row][mid+1...h]
if (mat[row,mid] <= x)
l = mid + 1;
// else search in mat[row][l...mid-1]
else
h = mid - 1;
}
// required column index number
return h;
}
// function to count elements smaller than
// or equal to x in a sorted matrix
static int countSmallElements(int[,] mat,
int n, int x)
{
// to get the row index number of the largest
// element smaller than equal to 'x' in mat[][]
int row_no = binarySearchOnRow(mat,
0, n - 1, x);
// if no such row exists
if (row_no == -1)
return 0;
// to get the column index number of
// the largest element smaller than
// equal to 'x' in mat[row_no][]
int col_no = binarySearchOnCol(mat,
0, n - 1, x, row_no);
316
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
// required count of elements
return ((row_no) * n) + (col_no + 1);
}
// Driver code
public static void Main () {
int [,]mat = { { 1, 4, 7, 8 },
{ 10, 10, 12, 14 },
{ 15, 26, 30, 31 },
{ 31, 42, 46, 50 } };
int n = 4;
int x = 31;
Console.WriteLine("Count = "
+ countSmallElements(mat, n, x));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP implementation to count
// elements smaller than or
// equal to x in a sorted matrix
// function returns the row index
// no of largest element smaller
// than equal to 'x' in first
// column of mat[][]. For duplicates
// it returns the last row index no.
// of occurrence of required element
// 'x'. If no such element exits then
// it returns -1.
function binarySearchOnRow($mat, $l,
$h, $x)
{
while ($l <= $h) {
$mid = floor(($l + $h) / 2);
// if 'x' is greater than
// or equal to mat[mid][0],
// then search in
// mat[mid+1...h][0]
if ($mat[$mid][0] <= $x)
317
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
$l = $mid + 1;
// else search in
// mat[l...mid-1][0]
else
$h = $mid - 1;
}
// required row index number
return $h;
}
// function returns the column
// index no of largest element
// smaller than equal to 'x'
// in mat[row][]. For duplicates
// it returns the last column
// index no of occurrence of
// required element 'x'.
function binarySearchOnCol($mat, $l,
$h, $x, $row)
{
while ($l <= $h) {
$mid = floor(($l + $h) / 2);
// if 'x' is greater than or
// equal to mat[row][mid],
// then search in
// mat[row][mid+1...h]
if ($mat[$row][$mid] <= $x)
$l = $mid + 1;
// else search in
// mat[row][l...mid-1]
else
$h = $mid - 1;
}
// required column
// index number
return $h;
}
// function to count elements
// smaller than or equal to x
// in a sorted matrix
function countSmallElements($mat,
$n, $x)
318
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
{
// to get the row index number
// of the largest element
// smaller than equal to 'x'
// in mat[][]
$row_no = binarySearchOnRow($mat, 0,
$n - 1, $x);
// if no such row exists
if ($row_no == -1)
return 0;
// to get the column index
// number of the largest element
// smaller than equal to 'x'
// in mat[row_no][]
$col_no = binarySearchOnCol($mat, 0,
$n - 1, $x, $row_no);
// required count of elements
return floor(($row_no) * $n) +
($col_no + 1);
}
// Driver Code
$mat = array(array(1, 4, 7, 8),
array(10, 10, 12, 14),
array(15, 26, 30, 31),
array(31, 42, 46, 50));
$n = 4;
$x = 31;
echo "Count = ", countSmallElements ($mat, $n, $x);
// This code is contributed by nitin mittal.
?>
Output:
Count = 13
319
Chapter 44. Count elements smaller than or equal to x in a sorted matrix
Source
https://www.geeksforgeeks.org/count-elements-smaller-equal-x-sorted-matrix/
320
Chapter 45
A simple Approach is to traverse the whole of matrix and check whether cell value is equal
to given x and then increase count value accordingly. Time complexity in this approach is
quite high and is equal to O(n^2).
321
Chapter 45. Count entries equal to x in a special matrix
An efficient approach is to only find the number of factors of given x in the range 0 to
x and also those factors (including divisor and quotient ) must be less than or equal to n
(order of matrix). In this case time complexity will be O(n).
C++
322
Chapter 45. Count entries equal to x in a special matrix
// driver program
int main()
{
int n = 8;
// we can manually assume matrix of order 8*8
// where mat[i][j] = i*j , 0<i,j<=n
int x = 24;
cout << count(n, x);
return 0;
}
Java
323
Chapter 45. Count entries equal to x in a special matrix
System.out.println(count(n, x));
}
}
/*This code is contributed by Danish kaleem*/
C#
324
Chapter 45. Count entries equal to x in a special matrix
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program for counting
// number of cell equals to
// given x
// function to count factors
// as number of cell
function c_ount ( $n, $x)
{
$Count = 0;
// traverse and find the factors
for ( $i = 1; $i <= $n and
$i <= $x ; $i++)
{
// x%i == 0 means i is
// factor of x x/i <= n
// means i and j are
// <= n (for i*j=x)
if ( $x / $i <= $n and
$x % $i == 0)
$Count++;
}
// return count
return $Count;
}
// Driver Code
$n = 8;
// we can manually assume
// matrix of order 8*8
// where mat[i][j] = i*j ,
// 0<i,j<=n
$x = 24;
echo c_ount($n, $x);
// This code is contributed by anuj_67.
?>
Output :
325
Chapter 45. Count entries equal to x in a special matrix
Source
https://www.geeksforgeeks.org/count-entries-equal-to-x-in-a-special-matrix/
326
Chapter 46
Count frequency of k in a
matrix of size n where matrix(i,
j) = i+j
Input : n = 4, k = 7
Output : 2
Explanation
The matrix will be
2 3 4 5
3 4 5 6
4 5 6 7
5 6 7 8
in the given matrix where M(i, j) = i+j,
frequency of 7 is 2
Input : n = 5, k = 4
Output : 3
Explanation
The matrix will be
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
327
Chapter 46. Count frequency of k in a matrix of size n where matrix(i, j) = i+j
6 7 8 9 10
Explanation
In the given matrix where M(i, j) = i+j,
frequency of 4 is 3
First method
1) Construct a matrix of size n*n.
2) Fill the value with M(i, j)=i+j.(recall that here base index is 1)
3) Iteratively traverse the matrix and and count the frequency of given element.
This method is not that much efficient because if the matrix size is very large it’s will result
in Time limit exceed.time complexity will be O(n^2).
Efficient method
In this method we avoid creating matrix of size n*n.
for example
if n = 10 the matrix will be
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
7 8 9 10 11 12 13 14 15 16
8 9 10 11 12 13 14 15 16 17
9 10 11 12 13 14 15 16 17 18
10 11 12 13 14 15 16 17 18 19
11 12 13 14 15 16 17 18 19 20
Now, notice how the values are same in the secondary Diagonal, and we can also find a
pattern in the count it increases like 1, 2, 3, 4,
here we can see that
if (n+1)>=k then frequency of k is k-1
else frequency will be 2*n+1-k
CPP
328
Chapter 46. Count frequency of k in a matrix of size n where matrix(i, j) = i+j
// Driver Code
int main()
{
int n = 4, k = 7;
int freq = find(n, k);
if (freq < 0)
cout << " element not exist \n ";
else
cout << " Frequency of " << k
<< " is " << freq << "\n";
return 0;
}
Java
329
Chapter 46. Count frequency of k in a matrix of size n where matrix(i, j) = i+j
Python3
C#
330
Chapter 46. Count frequency of k in a matrix of size n where matrix(i, j) = i+j
// Driver function
public static void Main()
{
int n = 4, k = 7;
int freq = find(n, k);
if (freq < 0)
Console.WriteLine(" element"
+ " not exist ");
else
Console.WriteLine(" Frequency"
+ " of " + k + " is " +
freq );
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to find the frequency of k
// in matrix where m(i, j)=i+j
function find($n, $k)
{
if ($n + 1 >= $k)
return ($k - 1);
else
return (2 * $n + 1 - $k);
}
// Driver Code
$n = 4;
$k = 7;
$freq = find($n, $k);
if ($freq < 0)
echo " element not exist \n ";
else
echo " Frequency of " , $k
, " is " , $freq , "\n";
// This code is contributed by anuj_67.
?>
Output:
331
Chapter 46. Count frequency of k in a matrix of size n where matrix(i, j) = i+j
Frequency of 7 is 2
Improved By : vt_m
Source
https://www.geeksforgeeks.org/count-frequency-k-matrix-size-n-matrixi-j-ij/
332
Chapter 47
• x1 � x2
• y1 � y2
• A[x2 ][y2 ] < A[x1 ][y1 ]
Constraints :
• 1 � Ai,j � 109
• 1 � N � 103
Examples:
1. Finding number of inversion pairs in a 1D array using Binary Indexed Tree (BIT)
https://www.geeksforgeeks.org/count-inversions-array-set-3-using-bit
333
Chapter 47. Count inversion pairs in a matrix
2. 2D BIT
https://www.geeksforgeeks.org/two-dimensional-binary-indexed-tree-or-fenwick-tree
Since, we need to find number of inversion pairs in a matrix, first thing we need to do is to
store the elements of the matrix in another array, say v and sort the array v so that we can
compare the elements of the unsorted matrix with v and find the number of inversion pairs
using BIT. But it is given that the values of the elements are very large (109 ), so we cannot
use the values of the elements in the matrix as indices in the BIT. Thus, we need to use the
position of the elements as indexes in the 2D BIT.
We are going to use the tuple (-A[i][j], i, j) for each element of the matrix and store it in an
array, say ‘v’. Then we need to sort v according to the value of -A[i][j] in ascending order,
so that the largest element of the matrix will be stored at index 0 and the smallest one at
the last index of v. Now, the problem is reduced to finding inversion pairs in a 1D array,
the only exception is that we are going to use a 2D BIT.
Note that here we are using negative values of A[i][j], simply because we are going to traverse
v from left to right, i.e., from the largest number in the matrix to the smallest one(because
that’s what we do when finding inversion pairs in a 1D array using BIT). One can also use
positive values and traverse v from right to left fashion, final result will remain same.
Algorithm :
334
Chapter 47. Count inversion pairs in a matrix
335
Chapter 47. Count inversion pairs in a matrix
336
Chapter 47. Count inversion pairs in a matrix
return inv_pair_cnt;
}
// Driver program
int main()
{
int mat[N][N] = { { 4, 7, 2, 9 },
{ 6, 4, 1, 7 },
{ 5, 3, 8, 1 },
{ 3, 2, 5, 6 } };
long long inv_pair_cnt = countInversionPairs(mat);
cout << "The number of inversion pairs are : "
<< inv_pair_cnt << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-inversion-pairs-matrix/
337
Chapter 48
Count number of islands where every island is row-wise and column-wise separated - Geeks-
forGeeks
Given a rectangular matrix which has only two possible values ‘X’ and ‘O’. The values ‘X’
always appear in form of rectangular islands and these islands are always row-wise and
column-wise separated by at least one line of ‘O’s. Note that islands can only be diagonally
adjacent. Count the number of islands in the given matrix.
Examples:
338
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated
We strongly recommend to minimize your browser and try this yourself first.
The idea is to count all top-leftmost corners of given matrix. We can check if a ‘X’ is top
left or not by checking following conditions.
1) A ‘X’ is top of rectangle if the cell just above it is a ‘O’
2) A ‘X’ is leftmost of rectangle if the cell just left of it is a ‘O’
Note that we must check for both conditions as there may be more than one top cells and
more than one leftmost cells in a rectangular island. Below is the implementation of above
idea.
C/C++
339
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated
return count;
}
// Driver program to test above function
int main()
{
int mat[M][N] = {{'O', 'O', 'O'},
{'X', 'X', 'O'},
{'X', 'X', 'O'},
{'O', 'O', 'X'},
{'O', 'O', 'X'},
{'X', 'X', 'O'}
};
cout << "Number of rectangular islands is "
<< countIslands(mat);
return 0;
}
Java
340
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated
count++;
}
}
}
return count;
}
// Driver program
public static void main (String[] args)
{
// Size of given matrix is m X n
int m = 6;
int n = 3;
int mat[][] = {{'O', 'O', 'O'},
{'X', 'X', 'O'},
{'X', 'X', 'O'},
{'O', 'O', 'X'},
{'O', 'O', 'X'},
{'X', 'X', 'O'}
};
System.out.println("Number of rectangular islands is: "
+ countIslands(mat, m, n));
}
}
// This code is contributed by Pramod Kumar
C#
341
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated
PHP
<?php
// A PHP program to count the
// number of rectangular islands
// where every island is separated
342
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated
// by a line
// Size of given matrix is M X N
// This function takes a matrix
// of 'X' and 'O' and returns the
// number of rectangular islands
// of 'X' where no two islands are
// row-wise or column-wise adjacent,
// the islands may be diagonaly
// adjacent
function countIslands($mat)
{
$M = 6;
$N = 3;
// Initialize result
$count = 0;
// Traverse the input matrix
for($i = 0; $i < $M; $i++)
{
for ($j = 0; $j < $N; $j++)
{
// If current cell is
// 'X', then check whether
// this is top-leftmost of a
// rectangle. If yes, then
// increment count
if ($mat[$i][$j] == 'X')
{
if (($i == 0 || $mat[$i - 1][$j] == 'O') &&
($j == 0 || $mat[$i][$j-1] == 'O'))
$count++;
}
}
}
return $count;
}
// Driver Code
$mat = array(array('O', 'O', 'O'),
array('X', 'X', 'O'),
array('X', 'X', 'O'),
array('O', 'O', 'X'),
array('O', 'O', 'X'),
array('X', 'X', 'O'));
343
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated
Output:
Source
https://www.geeksforgeeks.org/count-number-islands-every-island-separated-line/
344
Chapter 49
Input: m = 2, n = 2
Output: 5
There are 4 squares of size 1x1 +
1 square of size 2x2.
Input: m = 4, n = 3
Output: 20
There are 12 squares of size 1x1 +
6 squares of size 2x2 +
2 squares of size 3x3.
345
Chapter 49. Count number of squares in a rectangle
346
Chapter 49. Count number of squares in a rectangle
(n-m) x m x (m+1)/2
.
Using above logic for rectangle, we can also prove that number of squares in a square is
n(n+1)(2n+1)/6
Below is implementation of above formula.
CPP
Java
347
Chapter 49. Count number of squares in a rectangle
C#
348
Chapter 49. Count number of squares in a rectangle
}
// Now n is greater dimension, apply
// formula
return m * (m + 1) * (2 * m + 1) / 6 +
(n - m) * m * (m + 1) / 2;
}
// Driver method
public static void Main()
{
int m = 4, n = 3;
Console.WriteLine("Count of squares is "
+ countSquares(m, n));
}
}
//This code is contributed by vt_m.
PHP
<?php
// PHP program to count squares
// in a rectangle of size m x n
// Returns count of all squares
// in a rectangle of size m x n
function countSquares($m, $n)
{
// If n is smaller, swap m and n
if ($n < $m)
list($m, $n) = array($n, $m);
// Now n is greater dimension,
// apply formula
return $m * ($m + 1) * (2 * $m + 1) /
6 + ($n - $m) * $m * ($m + 1) / 2;
}
// Driver Code
$m = 4; $n = 3;
echo("Count of squares is " . countSquares($m, $n));
// This code is contributed by Ajit.
?>
Output :
349
Chapter 49. Count number of squares in a rectangle
Count of Squares is 20
Alternate Solution :
Let us take m = 2, n = 3;
The number of squares of side 1 will be 6 as there will be two cases one as squares of 1-unit
sides along the horizontal(2) and second case as squares of 1-unit sides along the vertical(3).
that give us 2*3 = 6 squares.
When the side is 2 units, one case will be as squares of side of 2 units along only one place
horizontally and second case as two places vertically. So number of squares=2
So we can deduce that
Number of squares of size 1*1 will be m*n
Number of squares of size 2*2 will be (n-1)(m-1)
So like this the number of squares of size n will be 1*(m-n+1)
The final formula for total number of squares will be n*(n+1)(3m-n+1)/6
Thanks to Pranav for providing this alternate solution.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/count-number-of-squares-in-a-rectangle/
350
Chapter 50
351
Chapter 50. Count number of ways to reach destination in a Maze
C++
352
Chapter 50. Count number of ways to reach destination in a Maze
}
// Similarly initialize the topmost row
for (int i=1; i<C; i++)
{
if (maze[0][i] == 0)
maze[0][i] = 1;
// If we encounter a blocked cell in bottommost
// row, there is no way of visiting any cell
// directly below it.
else
break;
}
// The only difference is that if a cell is -1,
// simply ignore it else recursively compute
// count value maze[i][j]
for (int i=1; i<R; i++)
{
for (int j=1; j<C; j++)
{
// If blockage is found, ignore this cell
if (maze[i][j] == -1)
continue;
// If we can reach maze[i][j] from maze[i-1][j]
// then increment count.
if (maze[i-1][j] > 0)
maze[i][j] = (maze[i][j] + maze[i-1][j]);
// If we can reach maze[i][j] from maze[i][j-1]
// then increment count.
if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);
}
}
// If the final cell is blocked, output 0, otherwise
// the answer
return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;
}
// Driver code
int main()
{
int maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
353
Chapter 50. Count number of ways to reach destination in a Maze
{-1, 0, 0, 0},
{0, 0, 0, 0}};
cout << countPaths(maze);
return 0;
}
Java
354
Chapter 50. Count number of ways to reach destination in a Maze
else
break;
}
// The only difference is that if a cell
// is -1, simply ignore it else recursively
// compute count value maze[i][j]
for (int i = 1; i < R; i++)
{
for (int j = 1; j <C ; j++)
{
// If blockage is found,
// ignore this cell
if (maze[i][j] == -1)
continue;
// If we can reach maze[i][j] from
// maze[i-1][j] then increment count.
if (maze[i - 1][j] > 0)
maze[i][j] = (maze[i][j] +
maze[i - 1][j]);
// If we can reach maze[i][j] from
// maze[i][j-1] then increment count.
if (maze[i][j - 1] > 0)
maze[i][j] = (maze[i][j] +
maze[i][j - 1]);
}
}
// If the final cell is blocked,
// output 0, otherwise the answer
return (maze[R - 1][C - 1] > 0) ?
maze[R - 1][C - 1] : 0;
}
// Driver code
public static void main (String[] args)
{
int maze[][] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
System.out.println (countPaths(maze));
}
355
Chapter 50. Count number of ways to reach destination in a Maze
}
// This code is contributed by vt_m
C#
356
Chapter 50. Count number of ways to reach destination in a Maze
break;
}
// The only difference is that if a cell
// is -1, simply ignore it else recursively
// compute count value maze[i][j]
for (int i = 1; i < R; i++)
{
for (int j = 1; j <C ; j++)
{
// If blockage is found,
// ignore this cell
if (maze[i,j] == -1)
continue;
// If we can reach maze[i][j] from
// maze[i-1][j] then increment count.
if (maze[i - 1,j] > 0)
maze[i,j] = (maze[i,j] +
maze[i - 1,j]);
// If we can reach maze[i][j] from
// maze[i][j-1] then increment count.
if (maze[i,j - 1] > 0)
maze[i,j] = (maze[i,j] +
maze[i,j - 1]);
}
}
// If the final cell is blocked,
// output 0, otherwise the answer
return (maze[R - 1,C - 1] > 0) ?
maze[R - 1,C - 1] : 0;
}
// Driver code
public static void Main ()
{
int [,]maze = { {0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
Console.Write (countPaths(maze));
}
}
357
Chapter 50. Count number of ways to reach destination in a Maze
PHP
<?php
// PHP program to count number
// of paths in a maze with obstacles.
$R = 4;
$C = 4;
// Returns count of possible
// paths in a maze[R][C]
// from (0,0) to (R-1,C-1)
function countPaths( $maze)
{
global $R, $C;
// If the initial cell is
// blocked, there is no
// way of moving anywhere
if ($maze[0][0] == - 1)
return 0;
// Initializing the
// leftmost column
for ( $i = 0; $i < $R; $i++)
{
if ($maze[$i][0] == 0)
$maze[$i][0] = 1;
// If we encounter a blocked
// cell in leftmost row,
// there is no way of
// visiting any cell
// directly below it.
else
break;
}
// Similarly initialize
// the topmost row
for($i = 1; $i < $C; $i++)
{
if ($maze[0][$i] == 0)
$maze[0][$i] = 1;
// If we encounter a blocked
358
Chapter 50. Count number of ways to reach destination in a Maze
359
Chapter 50. Count number of ways to reach destination in a Maze
Output:
Source
https://www.geeksforgeeks.org/count-number-ways-reach-destination-maze/
360
Chapter 51
Input: {8 27 39 589 23
23 34 589 12 45
939 32 27 12 78
23 349 48 21 32},
Input: {1, 2, 3
4, 5, 6},
arr[] = {2, 3, 4}
361
Chapter 51. Count of elements of an array present in every row of NxM matrix
A naive approach is to iterate for every element in the array arr[] and for ith row do a
linear search for every element in the array arr[]. Count the number of elements and print
the result for every row.
Time Complexity: O(N*M*L)
An efficient approach is to iterate for all the elements in the ith row of the matrix. Mark
all elements using a hash table. Iterate in the array of numbers in the Z array, check if the
number is present in the hash-table. Increase the count for every element present. Once all
the elements are checked, print the count.
Below is the implementation of the above approach:
362
Chapter 51. Count of elements of an array present in every row of NxM matrix
int main()
{
// NxM matrix
int a[][5] = { { 8, 27, 39, 589, 23 },
{ 23, 34, 589, 12, 45 },
{ 939, 32, 27, 12, 78 },
{ 23, 349, 48, 21, 32 } };
// elements array
int arr[] = { 589, 39, 27 };
int n = sizeof(a) / sizeof(a[0]);
int m = 5;
int l = sizeof(arr) / sizeof(arr[0]);
printCount(a, n, m, arr, l);
return 0;
}
Output:
row1 = 3
row2 = 1
row3 = 1
row4 = 0
Source
https://www.geeksforgeeks.org/count-of-elements-of-an-array-present-in-every-row-of-nxm-matrix/
363
Chapter 52
Input : a ={
{D,D,D,G,D,D},
{B,B,D,E,B,S},
{B,S,K,E,B,K},
{D,D,D,D,D,E},
{D,D,D,D,D,E},
{D,D,D,D,D,G}
}
str= "GEEKS"
Output :2
Input : a = {
{B,B,M,B,B,B},
{C,B,A,B,B,B},
{I,B,G,B,B,B},
{G,B,I,B,B,B},
{A,B,C,B,B,B},
{M,C,I,G,A,M}
}
str= "MAGIC"
364
Chapter 52. Count of number of given string in 2D character array
Output :3
365
Chapter 52. Count of number of given string in 2D character array
} else {
// through Backtrack searching
// in every directions
found += internalSearch(needle, row,
col+1, hay,
row_max, col_max);
found += internalSearch(needle, row, col-1,
hay, row_max, col_max);
found += internalSearch(needle, row+1, col,
hay, row_max, col_max);
found += internalSearch(needle, row-1, col,
hay, row_max, col_max);
}
hay[row][col] = match;
}
return found;
}
// Function to search the string in 2d array
int searchString(char *needle, int row, int col,
char **str, int row_count, int col_count)
{
int found = 0;
int r, c;
for (r = 0; r < row_count; ++r) {
for (c = 0; c < col_count; ++c) {
found += internalSearch(needle, r, c, str,
row_count - 1, col_count - 1);
}
}
return found;
}
// Driver code
int main(void){
char needle[] = "MAGIC";
char *input[] = {
"BBABBM",
"CBMBBA",
"IBABBG",
"GOZBBI",
"ABBBBC",
366
Chapter 52. Count of number of given string in 2D character array
"MCIGAM"
};
char *str[ARRAY_SIZE(input)];
int i;
for (i = 0; i < ARRAY_SIZE(input); ++i) {
str[i] = malloc(strlen(input[i]));
strcpy(str[i], input[i]);
}
printf("count: %d\n", searchString(needle, 0, 0,
str, ARRAY_SIZE(str), strlen(str[0])));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-count-number-given-string-present-2d-character-array/
367
Chapter 53
where
Examples :
Input : 1
Output : Number of walks possible is/are 0
Explanation :
0 because using just one step we can move to
any of the adjacent cells but we cannot trace
back to the original hexagon.
Input : 2
Output : Number of walks possible is/are 6
Input : 4
Output : Number of walks possible is/are 90
Approach :
• A hexagonal walk can be defined as walking through adjacent hexagons and returning
to the original cell. We know the fact that a hexagon contains six sides i.e. a hexagon
is surrounded by six hexagons. Now, we have to count number of ways we take N
steps and come back to the original hexagon.
368
Chapter 53. Count of possible hexagonal walks
• Now, let us suppose the original hexagon (where element X was initially present) to
be the origin. We need all possible ways we can take (N-k) steps such that we have
some steps which would trace back to our original hexagon. We can visualize this
hexagon and it’s related coordinate system from the picture below.
• Now, let’s assume, our element X was present at 0:0 of the given picture. Thus, we
can travel in six possible directions from a hexagon. Now, using the directions above
we memorize all possible movements such that we trace back to the original 0:0 index.
For memorizing we use a 3D array and we preprocess our answer for a given number
of steps and then query accordingly.
C++
369
Chapter 53. Count of possible hexagonal walks
370
Chapter 53. Count of possible hexagonal walks
int steps = 4;
cout << "Number of walks possible is/are "
<< list[steps] << endl;
return 0;
}
Java
371
Chapter 53. Count of possible hexagonal walks
// This array stores the number of
// ways possible for a given step
list[N] = ways[N][8][8];
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int list[] = new int[15];
// Preprocessing all possible ways
preprocess(list);
int steps = 4;
System.out.println( "Number of walks"
+ " possible is/are "+
list[steps] );
}
}
C#
// C# implementation of counting
// number of possible hexagonal walks
using System;
class GFG {
static int depth = 14;
static int [, ,]ways = new int[16,16,16];
// static int stepNum;
static void preprocess(int []list)
{
// We initialize our origin with 1
ways[0,8,8] = 1;
// For each N = 1 to 14, we traverse in
// all possible direction. Using this 3D
// array we calculate the number of ways
// at each step and the total ways for a
// given step shall be found at ways[step
// number][8][8] because all the steps
// after that will be used to trace back
// to the original point index 0:0
372
Chapter 53. Count of possible hexagonal walks
Output :
The time complexity of the above code is and the space complexity is
373
Chapter 53. Count of possible hexagonal walks
Source
https://www.geeksforgeeks.org/count-possible-hexagonal-walks/
374
Chapter 54
Count pairs from two sorted matrices with given sum - GeeksforGeeks
Given two sorted matrices mat1 and mat2 of size n x n of distinct elements. Given a value
x. The problem is to count all pairs from both matrices whose sum is equal to x.
Note: The pair has an element from each matrix. Matrices are strictly sorted which means
that matrices are sorted in a way such that all elements in a row are sorted in increasing
order and for row ‘i’, where 1 <= i <= n-1, first element of row ’i’ is greater than the last
element of row ’i-1’.
Examples:
Method 1 (Naive Approach): For each element ele of mat1[][] linearly search (x – ele)
in mat2[][].
C++
375
Chapter 54. Count pairs from two sorted matrices with given sum
376
Chapter 54. Count pairs from two sorted matrices with given sum
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
cout << "Count = "
<< countPairs(mat1, mat2, n, x);
return 0;
}
Java
377
Chapter 54. Count pairs from two sorted matrices with given sum
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
// if value (x-mat1[i][j]) is
// found in mat2[][]
if (valuePresent(mat2, n, x - mat1[i][j]))
count++;
}
// required count of pairs
return count;
}
// Driver program
public static void main (String[] args)
{
int mat1[][] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
System.out.println ("Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
Python3
378
Chapter 54. Count pairs from two sorted matrices with given sum
C#
379
Chapter 54. Count pairs from two sorted matrices with given sum
380
Chapter 54. Count pairs from two sorted matrices with given sum
int [,]mat1 = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int [,]mat2 = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
Console.WriteLine("Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
Output:
Count = 4
381
Chapter 54. Count pairs from two sorted matrices with given sum
382
Chapter 54. Count pairs from two sorted matrices with given sum
// else false
bool searchValue(int mat[][SIZE],
int n, int val)
{
// to get the row index number of the largest element
// smaller than equal to 'val' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, val);
// if no such row exists, then
// 'val' is not present
if (row_no == -1)
return false;
// to search 'val' in mat[row_no][]
return binarySearchOnCol(mat, 0, n - 1, val, row_no);
}
// function to count pairs from two sorted matrices
// whose sum is equal to a given value x
int countPairs(int mat1[][SIZE], int mat2[][SIZE],
int n, int x)
{
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// if value (x-mat1[i][j]) is found in mat2[][]
if (searchValue(mat2, n, x - mat1[i][j]))
count++;
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
int mat1[][SIZE] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
383
Chapter 54. Count pairs from two sorted matrices with given sum
Java
384
Chapter 54. Count pairs from two sorted matrices with given sum
{
int mid = (l + h) / 2;
// 'val' found
if (mat[row][mid] == val)
return true;
// search in mat[row][mid+1...h]
else if (mat[row][mid] < val)
l = mid + 1;
// search in mat[row][l...mid-1]
else
h = mid - 1;
}
// 'val' not found
return false;
}
// function to search 'val' in mat[][]
// returns true if 'val' is present
// else false
static boolean searchValue(int mat[][],
int n, int val)
{
// to get the row index number
// of the largest element smaller
// than equal to 'val' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, val);
// if no such row exists, then
// 'val' is not present
if (row_no == -1)
return false;
// to search 'val' in mat[row_no][]
return binarySearchOnCol(mat, 0, n - 1, val, row_no);
}
// function to count pairs from
// two sorted matrices whose sum
// is equal to a given value x
static int countPairs(int mat1[][], int mat2[][],
int n, int x)
{
int count = 0;
385
Chapter 54. Count pairs from two sorted matrices with given sum
C#
// C# implementation to count
// pairs from two sorted matrices
// whose sum is equal to a given
// value x
using System;
class GFG
{
//int SIZE= 10;
// function returns the row index no of largest
// element smaller than equal to 'x' in first
// column of mat[][]. If no such element exists
386
Chapter 54. Count pairs from two sorted matrices with given sum
387
Chapter 54. Count pairs from two sorted matrices with given sum
388
Chapter 54. Count pairs from two sorted matrices with given sum
Output:
Count = 4
389
Chapter 54. Count pairs from two sorted matrices with given sum
Output:
Count = 4
390
Chapter 54. Count pairs from two sorted matrices with given sum
this process until either of the two matrices gets completely traversed.
C++
391
Chapter 54. Count pairs from two sorted matrices with given sum
else
c2--;
// if 'c1' crosses right boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
int mat1[][SIZE] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
cout << "Count = "
<< countPairs(mat1, mat2, n, x);
return 0;
}
392
Chapter 54. Count pairs from two sorted matrices with given sum
Java
393
Chapter 54. Count pairs from two sorted matrices with given sum
// else move mat2[][] column
// 'c2' to left
else
c2--;
// if 'c1' crosses right boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver code
public static void main (String[] args)
{
int mat1[][] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
System.out.println ( "Count = " +
countPairs(mat1, mat2, n, x));
394
Chapter 54. Count pairs from two sorted matrices with given sum
}
}
// This article is contributed by vt_m
C#
395
Chapter 54. Count pairs from two sorted matrices with given sum
}
// if true, move mat1[][]
// column 'c1' to right
else if (val < x)
c1++;
// else move mat2[][] column
// 'c2' to left
else
c2--;
// if 'c1' crosses right
// boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left
// boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver code
public static void Main ()
{
int [,]mat1 = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int [,]mat2 = { { 2, 4, 7 },
{ 9, 10, 12 },
396
Chapter 54. Count pairs from two sorted matrices with given sum
Output:
Count = 4
Source
https://www.geeksforgeeks.org/count-pairs-two-sorted-matrices-given-sum/
397
Chapter 55
Input : n = 3
arr[][] = { {1, 2, 3},
{4, 5, 2},
{7, 9, 10}};
Output : 2
In first example sum of principal diagonal
= (1 + 5 + 10) = 16 and sum of secondary
diagonal = (3 + 5 + 7) = 15.
Input: n = 4
arr[][] = { { 7, 2, 3, 5 },
{ 4, 5, 6, 3 },
{ 7, 9, 10, 12 },
{ 1, 5, 4, 3 } };
Output: 1
We need to count number of rows or columns whose sum is equal to 16 or 15. So find sum
of all rows and columns and if their sum is equal to 16 or 15 then increment the count.
Therefore, sum of column {2, 5, 9} = 16 and sum column {3, 2, 10} = 15. Hence, the count
is equal to 2.
C++
398
Chapter 55. Count rows/columns with sum equals to diagonal sum
399
Chapter 55. Count rows/columns with sum equals to diagonal sum
int arr[n][n] = { { 7, 2, 3, 5 },
{ 4, 5, 6, 3 },
{ 7, 9, 10, 12 },
{ 1, 5, 4, 3 } };
cout << count(arr) << endl;
}
Java
400
Chapter 55. Count rows/columns with sum equals to diagonal sum
Python3
401
Chapter 55. Count rows/columns with sum equals to diagonal sum
diag2 += arr[i][j]
j -= 1
# Find the sum of individual
# row and column
for i in range(n):
row = 0; col = 0
for j in range(n):
row += arr[i][j]
for j in range(n):
col += arr[j][i]
if ((row == diag1) or (row == diag2)):
count += 1
if ((col == diag1) or (col == diag2)):
count += 1
return count
# Driver code
arr = [[ 7, 2, 3, 5 ],
[ 4, 5, 6, 3 ],
[ 7, 9, 10, 12 ],
[ 1, 5, 4, 3 ] ]
print(count(arr))
# This code is contributed by Anant Agarwal.
C#
402
Chapter 55. Count rows/columns with sum equals to diagonal sum
403
Chapter 55. Count rows/columns with sum equals to diagonal sum
{ 7, 9, 10, 12 },
{ 1, 5, 4, 3 } };
Console.Write(count(arr));
}
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to Count number of rows and
// columns having sum is equal to sum of
// any diagonal in matrix
// function to count number of
// rows countnd columns whose
// sum is equal to sum of any diagonal
function countt($arr)
{
$diag1 = 0; $diag2 = 0;
$row = 0; $col = 0;
$count = 0;$n = 4;
for ($i = 0, $j = $n - 1; $i < $n; $i++, $j--)
{
// sum of principle diagonal
$diag1 += $arr[$i][$i];
// sum of secondary diagonal
$diag2 += $arr[$i][$j];
}
// Find the sum of individual
// row and column
for ($i = 0; $i < $n; $i++) {
$row = 0; $col = 0;
for ($j = 0; $j < $n; $j++) {
$row = $row + $arr[$i][$j];
}
for ($j = 0; $j < $n; $j++) {
$col = $col + $arr[$j][$i];
}
if (($row == $diag1) || ($row == $diag2)) {
404
Chapter 55. Count rows/columns with sum equals to diagonal sum
$count++;
}
if (($col == $diag1) || ($col == $diag2))
$count++;
}
return $count;
}
// Driver code
{
$arr = array(array(7, 2, 3, 5),
array(4, 5, 6, 3),
array(7, 9, 10, 12),
array(1, 5, 4, 3));
echo countt($arr) ;
}
// This code is contributed by nitin mittal.
?>
Output:
Source
https://www.geeksforgeeks.org/count-rowscolumns-with-sum-equals-to-diagonal-sum/
405
Chapter 56
k = 4
Output : 6
The index range for the sub-matrices are:
(0, 0) to (0, 1)
(1, 0) to (2, 1)
(0, 0) to (2, 1)
(2, 1) to (2, 1)
(0, 1) to (1, 2)
(1, 2) to (1, 2)
Naive Approach: The naive solution for this problem is to check every possible rectangle
in given 2D array. This solution requires 4 nested loops and time complexity of this solution
would be O(n^4).
Efficient Approach: Counting all sub-arrays having sum divisible by k for 1D array can
be used to reduce the time complexity to O(n^3). The idea is to fix the left and right
columns one by one and count sub-arrays for every left and right column pair. Calculate
406
Chapter 56. Count sub-matrices having sum divisible ‘k’
sum of elements in every row from left to right and store these sums in an array say temp[].
So temp[i] indicates sum of elements from left to right in row i. Count sub-arrays in temp[]
having sum divisible by k. This count is the number of sub-matrices having sum divisible
by k with left and right as boundary columns. Sum up all the counts for each temp[] with
different left and right column pairs.
C++
407
Chapter 56. Count sub-matrices having sum divisible ‘k’
return result;
}
// function to count all sub-matrices having sum
// divisible by the value 'k'
int countSubmatrix(int mat[SIZE][SIZE], int n, int k)
{
// Variable to store the final output
int tot_count = 0;
int left, right, i;
int temp[n];
// Set the left column
for (left = 0; left < n; left++) {
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column
// set by outer loop
for (right = left; right < n; right++) {
// Calculate sum between current left
// and right for every row 'i'
for (i = 0; i < n; ++i)
temp[i] += mat[i][right];
// Count number of subarrays in temp[]
// having sum divisible by 'k' and then
// add it to 'tot_count'
tot_count += subCount(temp, n, k);
}
}
// required count of sub-matrices having sum
// divisible by 'k'
return tot_count;
}
// Driver program to test above
int main()
{
int mat[][SIZE] = { { 5, -1, 6 },
{ -2, 3, 8 },
{ 7, 4, -9 } };
int n = 3, k = 4;
408
Chapter 56. Count sub-matrices having sum divisible ‘k’
Java
409
Chapter 56. Count sub-matrices having sum divisible ‘k’
// add the subarrays starting from the arr[i]
// which are divisible by k itself
result += mod[0];
return result;
}
// function to count all sub-matrices
// having sum divisible by the value 'k'
static int countSubmatrix(int mat[][], int n, int k)
{
// Variable to store the final output
int tot_count = 0;
int left, right, i;
int temp[] = new int[n];
// Set the left column
for (left = 0; left < n; left++) {
// Initialize all elements of temp as 0
Arrays.fill(temp, 0);
// Set the right column for the left column
// set by outer loop
for (right = left; right < n; right++) {
// Calculate sum between current left
// and right for every row 'i'
for (i = 0; i < n; ++i)
temp[i] += mat[i][right];
// Count number of subarrays in temp[]
// having sum divisible by 'k' and then
// add it to 'tot_count'
tot_count += subCount(temp, n, k);
}
}
// required count of sub-matrices having sum
// divisible by 'k'
return tot_count;
}
// Driver code
public static void main(String[] args)
{
410
Chapter 56. Count sub-matrices having sum divisible ‘k’
Python3
# Python implementation to
# count sub-matrices having
# sum divisible by the
# value 'k'
# function to count all
# sub-arrays divisible by k
def subCount(arr, n, k) :
# create auxiliary hash
# array to count frequency
# of remainders
mod = [0] * k;
# Traverse original array
# and compute cumulative
# sum take remainder of
# this current cumulative
# sum and increase count
# by 1 for this remainder
# in mod array
cumSum = 0;
for i in range(0, n) :
cumSum = cumSum + arr[i];
# as the sum can be
# negative, taking
# modulo twice
mod[((cumSum % k) + k) % k] = mod[
((cumSum % k) + k) % k] + 1;
result = 0; # Initialize result
# Traverse mod
411
Chapter 56. Count sub-matrices having sum divisible ‘k’
for i in range(0, k) :
# If there are more than
# one prefix subarrays
# with a particular mod value.
if (mod[i] > 1) :
result = result + int((mod[i] *
(mod[i] - 1)) / 2);
# add the subarrays starting
# from the arr[i] which are
# divisible by k itself
result = result + mod[0];
return result;
# function to count all
# sub-matrices having sum
# divisible by the value 'k'
def countSubmatrix(mat, n, k) :
# Variable to store
# the final output
tot_count = 0;
temp = [0] * n;
# Set the left column
for left in range(0, n - 1) :
# Set the right column
# for the left column
# set by outer loop
for right in range(left, n) :
# Calculate sum between
# current left and right
# for every row 'i'
for i in range(0, n) :
temp[i] = (temp[i] +
mat[i][right]);
# Count number of subarrays
# in temp having sum
# divisible by 'k' and then
# add it to 'tot_count'
tot_count = (tot_count +
subCount(temp, n, k));
412
Chapter 56. Count sub-matrices having sum divisible ‘k’
# required count of
# sub-matrices having
# sum divisible by 'k'
return tot_count;
# Driver Code
mat = [[5, -1, 6],
[-2, 3, 8],
[7, 4, -9]];
n = 3;
k = 4;
print ("Count = {}" . format(
countSubmatrix(mat, n, k)));
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
// C# implementation to count
// sub-matrices having sum
// divisible by the value 'k'
using System;
class GFG
{
// function to count all
// sub-arrays divisible by k
static int subCount(int []arr,
int n, int k)
{
// create auxiliary hash
// array to count frequency
// of remainders
int []mod = new int[k];
// Traverse original array
// and compute cumulative
// sum take remainder of
// this current cumulative
// sum and increase count
// by 1 for this remainder
// in mod[] array
int cumSum = 0;
for (int i = 0; i < n; i++)
{
cumSum += arr[i];
413
Chapter 56. Count sub-matrices having sum divisible ‘k’
// as the sum can be negative,
// taking modulo twice
mod[((cumSum % k) + k) % k]++;
}
// Initialize result
int result = 0;
// Traverse mod[]
for (int i = 0; i < k; i++)
// If there are more than
// one prefix subarrays
// with a particular mod value.
if (mod[i] > 1)
result += (mod[i] *
(mod[i] - 1)) / 2;
// add the subarrays starting
// from the arr[i] which are
// divisible by k itself
result += mod[0];
return result;
}
// function to count all
// sub-matrices having sum
// divisible by the value 'k'
static int countSubmatrix(int [,]mat,
int n, int k)
{
// Variable to store
// the final output
int tot_count = 0;
int left, right, i;
int []temp = new int[n];
// Set the left column
for (left = 0; left < n; left++)
{
// Set the right column
// for the left column
// set by outer loop
for (right = left; right < n; right++)
{
414
Chapter 56. Count sub-matrices having sum divisible ‘k’
// Calculate sum between
// current left and right
// for every row 'i'
for (i = 0; i < n; ++i)
temp[i] += mat[i, right];
// Count number of subarrays
// in temp[] having sum
// divisible by 'k' and then
// add it to 'tot_count'
tot_count += subCount(temp, n, k);
}
}
// required count of
// sub-matrices having
// sum divisible by 'k'
return tot_count - 3;
}
// Driver code
static void Main()
{
int [,]mat = new int[,]{{5, -1, 6},
{-2, 3, 8},
{7, 4, -9}};
int n = 3, k = 4;
Console.Write("\nCount = " +
countSubmatrix(mat, n, k));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// PHP implementation to
// count sub-matrices having
// sum divisible by the
// value 'k'
// function to count all
// sub-arrays divisible by k
function subCount($arr, $n, $k)
{
415
Chapter 56. Count sub-matrices having sum divisible ‘k’
416
Chapter 56. Count sub-matrices having sum divisible ‘k’
417
Chapter 56. Count sub-matrices having sum divisible ‘k’
array(-2, 3, 8),
array(7, 4, -9));
$n = 3; $k = 4;
echo ("Count = " .
countSubmatrix($mat, $n, $k));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
Count = 6
Source
https://www.geeksforgeeks.org/count-sub-matrices-sum-divisible-k/
418
Chapter 57
Count zeros in a row wise and column wise sorted matrix - GeeksforGeeks
Given a N x N binary matrix (elements in matrix can be either 1 or 0) where each row and
column of the matrix is sorted in ascending order, count number of 0s present in it.
Expected time complexity is O(N).
Examples:
Input:
[0, 0, 0, 0, 1]
[0, 0, 0, 1, 1]
[0, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
Output: 8
Input:
[0, 0]
[0, 0]
Output: 4
Input:
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1]
419
Chapter 57. Count zeros in a row wise and column wise sorted matrix
[1, 1, 1, 1]
Output: 0
The idea is very simple. We start from the bottom-left corner of the matrix and repeat
below steps until we find the top or right edge of the matrix.
1. Decrement row index until we find a 0.
2. Add number of 0s in current column i.e. current row index + 1 to the result and move
right to next column (Increment col index by 1).
The above logic will work since the matrix is row-wise and column-wise sorted. The logic
will also work for any matrix containing non-negative integers.
Below is the implementation of above idea :
C++
420
Chapter 57. Count zeros in a row wise and column wise sorted matrix
}
return count;
}
// Driver Program to test above functions
int main()
{
int mat[N][N] =
{
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 }
};
cout << countZeroes(mat);
return 0;
}
Java
421
Chapter 57. Count zeros in a row wise and column wise sorted matrix
Python
422
Chapter 57. Count zeros in a row wise and column wise sorted matrix
C#
423
Chapter 57. Count zeros in a row wise and column wise sorted matrix
// Function to count number of
// 0s in the given row-wise and
// column-wise sorted binary matrix.
static int countZeroes(int [,] mat)
{
// start from bottom-left
// corner of the matrix
int row = N - 1, col = 0;
// stores number of zeroes
// in the matrix
int count = 0;
while (col < N)
{
// move up until you find a 0
while (mat[row,col] > 0)
// if zero is not found in
// current column,
// we are done
if (--row < 0)
return count;
// add 0s present in current
// column to result
count += (row + 1);
// move right to next column
col++;
}
return count;
}
// Driver Code
public static void Main ()
{
int [,] mat = { { 0, 0, 0, 0, 1 },
{ 0, 0, 0, 1, 1 },
{ 0, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1 } };
Console.WriteLine(countZeroes(mat));
}
}
424
Chapter 57. Count zeros in a row wise and column wise sorted matrix
PHP
<?php
// PHP program to count number
// of 0s in the given row-wise
// and column-wise sorted
// binary matrix.
// Function to count number
// of 0s in the given
// row-wise and column-wise
// sorted binary matrix.
function countZeroes($mat)
{
// start from bottom-left
// corner of the matrix
$N = 5;
$row = $N - 1;
$col = 0;
// stores number of
// zeroes in the matrix
$count = 0;
while ($col < $N)
{
// move up until
// you find a 0
while ($mat[$row][$col])
// if zero is not found
// in current column, we
// are done
if (--$row < 0)
return $count;
// add 0s present in
// current column to result
$count += ($row + 1);
// move right to
// next column
$col++;
}
return $count;
425
Chapter 57. Count zeros in a row wise and column wise sorted matrix
}
// Driver Code
$mat = array(array(0, 0, 0, 0, 1),
array(0, 0, 0, 1, 1),
array(0, 1, 1, 1, 1),
array(1, 1, 1, 1, 1),
array(1, 1, 1, 1, 1));
echo countZeroes($mat);
// This code is contributed by Sam007
?>
Output:
Time complexity of above solution is O(n) since the solution follows single path from
bottom-left corner to top or right edge of the matrix.
Auxiliary space used by the program is O(1).
Do share with us if you find more interesting methods of solving this problem.
Improved By : KRV, Sam007, Chandan_Kumar
Source
https://www.geeksforgeeks.org/count-zeros-in-a-row-wise-and-column-wise-sorted-matrix/
426
Chapter 58
Input: 1 0 1
0 1 0
Output: 8
Explanation: There are six one-element sets
(three 1s and three 0s). There are two two-
element sets, the first one consists of the
first and the third cells of the first row.
The second one consists of the first and the
third cells of the second row.
Input: 1 0
1 1
Output: 6
427
Chapter 58. Counting sets of 1s and 0s in a binary matrix
// in a binary matrix.
#include <bits/stdc++.h>
using namespace std;
const int m = 3; // no of columns
const int n = 2; // no of rows
// function to calculate the number of
// non empty sets of cell
long long countSets(int a[n][m])
{
// stores the final answer
long long res = 0;
// traverses row-wise
for (int i = 0; i < n; i++)
{
int u = 0, v = 0;
for (int j = 0; j < m; j++)
a[i][j] ? u++ : v++;
res += pow(2,u)-1 + pow(2,v)-1;
}
// traverses column wise
for (int i = 0; i < m; i++)
{
int u = 0, v = 0;
for (int j = 0; j < n; j++)
a[j][i] ? u++ : v++;
res += pow(2,u)-1 + pow(2,v)-1;
}
// at the end subtract n*m as no of
// single sets have been added twice.
return res-(n*m);
}
// driver program to test the above function.
int main() {
int a[][3] = {(1, 0, 1),
(0, 1, 0)};
cout << countSets(a);
return 0;
}
428
Chapter 58. Counting sets of 1s and 0s in a binary matrix
Java
429
Chapter 58. Counting sets of 1s and 0s in a binary matrix
System.out.print(countSets(a));
}
}
// This code is contributed by Anant Agarwal.
C#
430
Chapter 58. Counting sets of 1s and 0s in a binary matrix
u++;
else
v++;
}
res += (long)(Math.Pow(2, u) - 1
+ Math.Pow(2, v)) - 1;
}
// at the end subtract n*m as no of
// single sets have been added twice.
return res - (n * m);
}
// Driver code
public static void Main()
{
int [,]a = {{1, 0, 1}, {0, 1, 0}};
Console.WriteLine(countSets(a));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to compute
// number of sets
// in a binary matrix.
// no of columns
$m = 3;
// no of rows
$n = 2;
// function to calculate the number
// of non empty sets of cell
function countSets($a)
{
global $m, $n;
// stores the final answer
$res = 0;
// traverses row-wise
for ($i = 0; $i < $n; $i++)
431
Chapter 58. Counting sets of 1s and 0s in a binary matrix
{
$u = 0; $v = 0;
for ( $j = 0; $j < $m; $j++)
$a[$i][$j] ? $u++ : $v++;
$res += pow(2, $u) - 1 + pow(2, $v) - 1;
}
// traverses column wise
for ($i = 0; $i < $m; $i++)
{
$u = 0;$v = 0;
for ($j = 0; $j < $n; $j++)
$a[$j][$i] ? $u++ : $v++;
$res += pow(2, $u) - 1 +
pow(2, $v) - 1;
}
// at the end subtract
// n*m as no of single
// sets have been added
// twice.
return $res-($n*$m);
}
// Driver Code
$a = array(array(1, 0, 1),
array(0, 1, 0));
echo countSets($a);
// This code is contributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/counting-sets-of-1s-and-0s-in-a-binary-matrix/
432
Chapter 59
Input : 3 6
Output : Number of Paths 84
Input : 3 0
Output : Number of Paths 1
433
Chapter 59. Counts paths from a point to reach Origin
As we are restricted to move down and left only we would run a recursive loop for each of
the combinations of the
steps that can be taken.
434
Chapter 59. Counts paths from a point to reach Origin
C++
Java
435
Chapter 59. Counts paths from a point to reach Origin
return 1;
// Else count sum of both ways
return (countPaths(n - 1, m) + countPaths(n, m - 1));
}
// Driver Code
public static void main (String[] args)
{
int n = 3, m = 2;
System.out.println (" Number of Paths "
+ countPaths(n, m));
}
}
// This code is contributed by vt_m
Python3
C#
436
Chapter 59. Counts paths from a point to reach Origin
PHP
<?php
// PHP program to count total number
// of paths from a point to origin
// Recursive function to
// count number of paths
function countPaths($n, $m)
{
// If we reach bottom or
// top left, we are
// have only one way to
437
Chapter 59. Counts paths from a point to reach Origin
Output:
Number of Paths 10
We can use Dynamic Programming as there are overlapping subproblems. We can draw
recursion tree to see overlapping problems. For example, in case of countPaths(4, 4), we
compute countPaths(3, 3) multiple times.
C++
438
Chapter 59. Counts paths from a point to reach Origin
Java
439
Chapter 59. Counts paths from a point to reach Origin
}
}
// This code is contributed by vt_m
C#
440
Chapter 59. Counts paths from a point to reach Origin
PHP
<?php
// PHP program to count total number of
// paths from a point to origin
// DP based function to
// count number of paths
function countPaths($n, $m)
{
//$dp[$n+1][$m+1];
// Fill entries in bottommost
// row and leftmost columns
for ($i = 0; $i <= $n; $i++)
$dp[$i][0] = 1;
for ($i = 0; $i <= $m; $i++)
$dp[0][$i] = 1;
// Fill DP in bottom up manner
for ($i = 1; $i <= $n; $i++)
for ($j = 1; $j <= $m; $j++)
$dp[$i][$j] = $dp[$i - 1][$j] +
$dp[$i][$j - 1];
return $dp[$n][$m];
}
// Driver Code
$n = 3;
$m = 2;
echo " Number of Paths " , countPaths($n, $m);
// This code is contributed by m_kit
?>
Output:
Number of Paths 10
Source
https://www.geeksforgeeks.org/counts-paths-point-reach-origin/
441
Chapter 60
Input: m = 3, n = 3
Output: Following matrix
X X X
X 0 X
X X X
Input: m = 4, n = 5
Output: Following matrix
X X X X X
X 0 0 0 X
X 0 0 0 X
X X X X X
Input: m = 5, n = 5
Output: Following matrix
X X X X X
X 0 0 0 X
X 0 X 0 X
442
Chapter 60. Create a matrix with alternating rectangles of O and X
X 0 0 0 X
X X X X X
Input: m = 6, n = 7
Output: Following matrix
X X X X X X X
X 0 0 0 0 0 X
X 0 X X X 0 X
X 0 X X X 0 X
X 0 0 0 0 0 X
X X X X X X X
We strongly recommend to minimize the browser and try this yourself first.
This question was asked in campus recruitment of Shreepartners Gurgaon. I followed the
following approach.
1) Use the code for Printing Matrix in Spiral form.
2) Instead of printing the array, inserted the element ‘X’ or ‘0’ alternatively in the array.
Following is implementation of the above approach.
CPP
#include <stdio.h>
// Function to print alternating rectangles of 0 and X
void fill0X(int m, int n)
{
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator */
int i, k = 0, l = 0;
// Store given number of rows and columns for later use
int r = m, c = n;
// A 2D array to store the output to be printed
char a[m][n];
char x = 'X'; // Iniitialize the character to be stoed in a[][]
// Fill characters in a[][] in spiral form. Every iteration fills
// one rectangle of either Xs or Os
while (k < m && l < n)
{
/* Fill the first row from the remaining rows */
for (i = l; i < n; ++i)
443
Chapter 60. Create a matrix with alternating rectangles of O and X
a[k][i] = x;
k++;
/* Fill the last column from the remaining columns */
for (i = k; i < m; ++i)
a[i][n-1] = x;
n--;
/* Fill the last row from the remaining rows */
if (k < m)
{
for (i = n-1; i >= l; --i)
a[m-1][i] = x;
m--;
}
/* Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
a[i][l] = x;
l++;
}
// Flip character for next iteration
x = (x == '0')? 'X': '0';
}
// Print the filled matrix
for (i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
printf("%c ", a[i][j]);
printf("\n");
}
}
/* Driver program to test above functions */
int main()
{
puts("Output for m = 5, n = 6");
fill0X(5, 6);
puts("\nOutput for m = 4, n = 4");
fill0X(4, 4);
puts("\nOutput for m = 3, n = 4");
fill0X(3, 4);
444
Chapter 60. Create a matrix with alternating rectangles of O and X
return 0;
}
Java
445
Chapter 60. Create a matrix with alternating rectangles of O and X
n--;
/* Fill the last row from the remaining rows */
if (k < m)
{
for (i = n-1; i >= l; --i)
a[m-1][i] = x;
m--;
}
/* Print the first column
// from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
a[i][l] = x;
l++;
}
// Flip character for next iteration
x = (x == '0')? 'X': '0';
}
// Print the filled matrix
for (i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
}
/* Driver program to test above functions */
public static void main (String[] args) {
System.out.println("Output for m = 5, n = 6");
fill0X(5, 6);
System.out.println("Output for m = 4, n = 4");
fill0X(4, 4);
System.out.println("Output for m = 3, n = 4");
fill0X(3, 4);
}
}
// This code is contributed by vt_m
446
Chapter 60. Create a matrix with alternating rectangles of O and X
C#
447
Chapter 60. Create a matrix with alternating rectangles of O and X
/* Fill the last row from the
remaining rows */
if (k < m)
{
for (i = n-1; i >= l; --i)
a[m-1,i] = x;
m--;
}
/* Print the first column
from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
a[i,l] = x;
l++;
}
// Flip character for next
// iteration
x = (x == '0')? 'X': '0';
}
// Print the filled matrix
for (i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
Console.Write(a[i,j] + " ");
Console.WriteLine();
}
}
/* Driver program to test
above functions */
public static void Main ()
{
Console.WriteLine("Output for"
+ " m = 5, n = 6");
fill0X(5, 6);
Console.WriteLine("Output for"
+ " m = 4, n = 4");
fill0X(4, 4);
Console.WriteLine("Output for"
+ " m = 3, n = 4");
fill0X(3, 4);
448
Chapter 60. Create a matrix with alternating rectangles of O and X
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP programt to Create a matrix with
// alternating rectangles of O and X
// Function to print alternating
// rectangles of 0 and X
function fill0X($m, $n)
{
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator */
$k = 0;
$l = 0;
// Store given number of rows
// and columns for later use
$r = $m;
$c = $n;
// A 2D array to store the
// output to be printed
// Iniitialize the character
// to be stoed in a[][]
$x = 'X';
// Fill characters in a[][] in
// spiral form. Every iteration fills
// one rectangle of either Xs or Os
while ($k < $m && $l < $n)
{
/* Fill the first row from
the remaining rows */
for ($i = $l; $i < $n; ++$i)
$a[$k][$i] = $x;
$k++;
/* Fill the last column from
449
Chapter 60. Create a matrix with alternating rectangles of O and X
450
Chapter 60. Create a matrix with alternating rectangles of O and X
?>
Output:
Output for m = 5, n = 6
X X X X X X
X 0 0 0 0 X
X 0 X X 0 X
X 0 0 0 0 X
X X X X X X
Output for m = 4, n = 4
X X X X
X 0 0 X
X 0 0 X
X X X X
Output for m = 3, n = 4
X X X X
X 0 0 X
X X X X
Source
https://www.geeksforgeeks.org/create-a-matrix-with-alternating-rectangles-of-0-and-x/
451
Chapter 61
Determinant of a Matrix
452
Chapter 61. Determinant of a Matrix
Determinant of 3 x 3 Matrix:
C++
453
Chapter 61. Determinant of a Matrix
{
for (int col = 0; col < n; col++)
{
// Copying into temporary matrix only those element
// which are not in given row and column
if (row != p && col != q)
{
temp[i][j++] = mat[row][col];
// Row is filled, so increase row index and
// reset col index
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
/* Recursive function for finding determinant of matrix.
n is current dimension of mat[][]. */
int determinantOfMatrix(int mat[N][N], int n)
{
int D = 0; // Initialize result
// Base case : if matrix contains single element
if (n == 1)
return mat[0][0];
int temp[N][N]; // To store cofactors
int sign = 1; // To store sign multiplier
// Iterate for each element of first row
for (int f = 0; f < n; f++)
{
// Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n);
D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1);
// terms are to be added with alternate sign
sign = -sign;
}
return D;
}
454
Chapter 61. Determinant of a Matrix
/* function for displaying the matrix */
void display(int mat[N][N], int row, int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
printf(" %d", mat[i][j]);
printf("n");
}
}
// Driver program to test above functions
int main()
{
/* int mat[N][N] = {{6, 1, 1},
{4, -2, 5},
{2, 8, 7}}; */
int mat[N][N] = {{1, 0, 2, -1},
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}
};
printf("Determinant of the matrix is : %d",
determinantOfMatrix(mat, N));
return 0;
}
Java
455
Chapter 61. Determinant of a Matrix
456
Chapter 61. Determinant of a Matrix
C#
457
Chapter 61. Determinant of a Matrix
static int N = 4;
// Function to get cofactor of
// mat[p][q] in temp[][]. n is
// current dimension of mat[][]
static void getCofactor(int [,]mat,
int [,]temp,
int p,
int q,
int n)
{
int i = 0, j = 0;
// Looping for each element of
// the matrix
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
// Copying into temporary matrix
// only those element which are
// not in given row and column
if (row != p && col != q)
{
temp[i, j++] = mat[row, col];
// Row is filled, so increase
// row index and reset col
//index
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
/* Recursive function for
finding determinant
of matrix. n is current
dimension of mat[][]. */
static int determinantOfMatrix(int [,]mat,
int n)
{
int D = 0; // Initialize result
458
Chapter 61. Determinant of a Matrix
// Base case : if matrix
// contains single
// element
if (n == 1)
return mat[0, 0];
// To store cofactors
int [,]temp = new int[N, N];
// To store sign multiplier
int sign = 1;
// Iterate for each element
// of first row
for (int f = 0; f < n; f++)
{
// Getting Cofactor of mat[0][f]
getCofactor(mat, temp, 0, f, n);
D += sign * mat[0, f]
* determinantOfMatrix(temp, n - 1);
// terms are to be added with
// alternate sign
sign = -sign;
}
return D;
}
/* function for displaying
the matrix */
static void display(int [,]mat,
int row,
int col)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
Console.Write(mat[i,j]);
Console.Write("\n");
}
}
// Driver code
public static void Main ()
459
Chapter 61. Determinant of a Matrix
{
int [,]mat = {{1, 0, 2, -1},
{3, 0, 0, 5},
{2, 1, 4, -3},
{1, 0, 5, 0}};
Console.Write("Determinant " +
"of the matrix is : "+
determinantOfMatrix(mat, N));
}
}
// This code is contributed by nitin mittal.
Output:
Source
https://www.geeksforgeeks.org/determinant-of-a-matrix/
460
Chapter 62
Input : A = { { 3, -2, 1 },
{ 1, -3, 2 },
461
Chapter 62. Diagonally Dominant Matrix
{ -1, 2, 4 } };
Output : YES
Given matrix is diagonally dominant
because absolute value of every diagonal
element is more than sum of absolute values
of corresponding row.
Input : A = { { -2, 2, 1 },
{ 1, 3, 2 },
{ 1, -2, 0 } };
Output : NO
The idea is to run a loop from i = 0 to n-1 for the number of rows and for each row, run
a loop j = 0 to n-1 find the sum of non-diagonal element i.e i != j. And check if diagonal
element is greater than or equal to sum. If for any row, it is false, then return false or print
“No”. Else print “YES”.
C++
462
Chapter 62. Diagonally Dominant Matrix
return true;
}
// Driven Program
int main()
{
int n = 3;
int m[N][N] = { { 3, -2, 1 },
{ 1, -3, 2 },
{ -1, 2, 4 } };
(isDDM(m, n)) ? (cout << "YES") : (cout << "NO");
return 0;
}
Java
463
Chapter 62. Diagonally Dominant Matrix
return true;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 3;
int m[][] = { { 3, -2, 1 },
{ 1, -3, 2 },
{ -1, 2, 4 } };
if (isDDM(m, n))
System.out.println("YES") ;
else
System.out.println("NO");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
464
Chapter 62. Diagonally Dominant Matrix
C#
465
Chapter 62. Diagonally Dominant Matrix
PHP
<?php
// PHP Program to check whether
// given matrix is Diagonally
// Dominant Matrix.
// check the given given matrix
// is Diagonally Dominant Matrix or not.
function isDDM( $m, $n)
{
// for each row
for ($i = 0; $i < $n; $i++)
{
// for each column, finding
// sum of each row.
$sum = 0;
for ( $j = 0; $j < $n; $j++)
$sum += abs($m[$i][$j]);
// removing the diagonal element.
466
Chapter 62. Diagonally Dominant Matrix
$sum -= abs($m[$i][$i]);
// checking if diagonal element
// is less than sum of non-diagonal
// element.
if (abs($m[$i][$i]) < $sum)
return false;
}
return true;
}
// Driver Code
$n = 3;
$m = array(array( 3, -2, 1 ),
array( 1, -3, 2 ),
array( -1, 2, 4 ));
if((isDDM($m, $n)))
echo "YES";
else
echo"NO";
// This code is contributed by SanjuTomar
?>
Output :
YES
Source
https://www.geeksforgeeks.org/diagonally-dominant-matrix/
467
Chapter 63
Different Operations on
Matrices
for i in 1 to m
for j in 1 to n
cij = aij + bij
Key points:
468
Chapter 63. Different Operations on Matrices
Matrices Subtraction –
The subtraction of two matrices Am*n and Bm*n gives a matrix Cm*n . The elements of C
are difference of corresponding elements in A and B which can be represented as:
for i in 1 to m
for j in 1 to n
cij = aij-bij
Key points:
Matrices Multiplication –
The multiplication of two matrices Am*n and Bn*p gives a matrix Cm*p . It means number
of columns in A must be equal to number of rows in B to calculate C=A*B. To calculate
element c11, multiply elements of 1st row of A with 1st column of B and add them (5*1+6*4)
which can be shown as:
The algorithm for multiplication of matrices A with order m*n and B with order n*p can
be written as:
for i in 1 to m
for j in 1 to p
cij = 0
for k in 1 to n
cij += aik*bkj
Key points:
469
Chapter 63. Different Operations on Matrices
Source
https://www.geeksforgeeks.org/different-operation-matrices/
470
Chapter 64
Input : R = 1, C = 1
Output : Right
Input : R = 2, C = 2
Output : Left
Input : R = 3, C = 1
Output : Down
Input : R = 3, C = 3
Output : Right
Simple Solution: One simple solution for this problem is to make it R x C matrix initialized
with zero and traverse it in spiral form and take a variable ‘Dir’ that tells the current
direction. Whenever we are at the end of any row and column take “Right” and change the
value of ‘Dir’ according to your current direction. Now follow the given conditions :
• If you are traversing top row, then your current direction is “Right”.
471
Chapter 64. Direction at last square block
When we reach at the last square, just print current direction i.e; value of ‘Dir’ variable.
Time and space complexity for this problem is O(R x C) and this will work only for small
values of R, C but here R and C are too large so creating R x C matrix is not possible for
too large values of R and C.
Efficient Approach : This approach requires little observation and some pen paper work.
Here we have to consider all the possible cases for R and C, then we just need to put IF
condition for all the possible cases. Here we are with all the possible conditions :
C++
472
Chapter 64. Direction at last square block
Java
473
Chapter 64. Direction at last square block
// Function which tells the Current direction
static void direction(int R, int C)
{
if (R != C && R % 2 == 0 && C % 2 != 0 && R < C) {
System.out.println("Left");
return;
}
if (R != C && R % 2 != 0 && C % 2 == 0 && R > C) {
System.out.println("Up");
return;
}
if (R == C && R % 2 != 0 && C % 2 != 0) {
System.out.println("Right");
return;
}
if (R == C && R % 2 == 0 && C % 2 == 0) {
System.out.println("Left");
return;
}
if (R != C && R % 2 != 0 && C % 2 != 0 && R < C) {
System.out.println("Right");
return;
}
if (R != C && R % 2 != 0 && C % 2 != 0 && R > C) {
System.out.println("Down");
return;
}
if (R != C && R % 2 == 0 && C % 2 == 0 && R < C) {
System.out.println("Left");
return;
}
if (R != C && R % 2 == 0 && C % 2 == 0 && R > C) {
System.out.println("Up");
return;
}
if (R != C && R % 2 == 0 && C % 2 != 0 && R > C) {
System.out.println("Down");
return;
}
if (R != C && R % 2 != 0 && C % 2 == 0 && R < C) {
System.out.println("Right");
return;
}
}
// Driver code
public static void main(String[] args)
474
Chapter 64. Direction at last square block
{
int R = 3, C = 1;
direction(R, C);
}
}
// This code is contributed by KRV.
C#
475
Chapter 64. Direction at last square block
{
Console.WriteLine("Right");
return;
}
if (R != C && R % 2 != 0 &&
C % 2 != 0 && R > C)
{
Console.WriteLine("Down");
return;
}
if (R != C && R % 2 == 0 &&
C % 2 == 0 && R < C)
{
Console.WriteLine("Left");
return;
}
if (R != C && R % 2 == 0 &&
C % 2 == 0 && R > C)
{
Console.WriteLine("Up");
return;
}
if (R != C && R % 2 == 0 &&
C % 2 != 0 && R > C)
{
Console.WriteLine("Down");
return;
}
if (R != C && R % 2 != 0 &&
C % 2 == 0 && R < C)
{
Console.WriteLine("Right");
return;
}
}
// Driver code
static public void Main ()
{
int R = 3, C = 1;
direction(R, C);
}
}
// This code is contributed by m_kit
PHP
476
Chapter 64. Direction at last square block
<?php
// PHP program to tell the Current
// direction in R x C grid
// Function which tells
// the Current direction
function direction($R, $C)
{
if ($R != $C && $R % 2 == 0 &&
$C % 2 != 0 && $R < $C)
{
echo "Left" ,"\n";
return;
}
if ($R != $C && $R % 2 != 0 &&
$C % 2 == 0 && $R > $C)
{
echo "Up" ,"\n";
return;
}
if ($R == $C && $R % 2 != 0
&& $C % 2 != 0)
{
echo "Right" ,"\n";
return;
}
if ($R == $C && $R % 2 == 0
&& $C % 2 == 0)
{
echo "Left" ,"\n";
return;
}
if ($R != $C && $R % 2 != 0 &&
$C % 2 != 0 && $R < $C)
{
echo "Right" ,"\n";
return;
}
if ($R != $C && $R % 2 != 0 &&
$C % 2 != 0 && $R > $C)
{
echo "Down" ,"\n";
return;
}
if ($R != $C && $R % 2 == 0 &&
$C % 2 == 0 && $R < $C)
{
echo "Left" ,"\n";
477
Chapter 64. Direction at last square block
return;
}
if ($R != $C && $R % 2 == 0 &&
$C % 2 == 0 && $R > $C)
{
echo "Up" ,"\n";
return;
}
if ($R != $C && $R % 2 == 0 &&
$C % 2 != 0 && $R > $C)
{
echo "Down" ,"\n";
return;
}
if ($R != $C && $R % 2 != 0 &&
$C % 2 == 0 && $R < $C)
{
echo "Right" ,"\n";
return;
}
}
// Driver Code
$R = 3; $C = 1;
direction($R, $C);
// This code is contributed by aj_36
?>
Output :
Down
Source
https://www.geeksforgeeks.org/direction-last-square-block/
478
Chapter 65
479
Chapter 65. Discrete Cosine Transform (Algorithm and Program)
480
Chapter 65. Discrete Cosine Transform (Algorithm and Program)
}
dct[i][j] = ci * cj * sum;
}
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%f\t", dct[i][j]);
}
printf("\n");
}
}
// Driver code
int main()
{
int matrix[m][n] = { { 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 } };
dctTransform(matrix);
return 0;
}
Java
481
Chapter 65. Discrete Cosine Transform (Algorithm and Program)
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
// ci and cj depends on frequency as well as
// number of row and columns of specified matrix
if (i == 0)
ci = 1 / Math.sqrt(m);
else
ci = Math.sqrt(2) / Math.sqrt(m);
if (j == 0)
cj = 1 / Math.sqrt(n);
else
cj = Math.sqrt(2) / Math.sqrt(n);
// sum will temporarily store the sum of
// cosine signals
sum = 0;
for (k = 0; k < m; k++)
{
for (l = 0; l < n; l++)
{
dct1 = matrix[k][l] *
Math.cos((2 * k + 1) * i * pi / (2 * m)) *
Math.cos((2 * l + 1) * j * pi / (2 * n));
sum = sum + dct1;
}
}
dct[i][j] = ci * cj * sum;
}
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
System.out.printf("%f\t", dct[i][j]);
System.out.println();
}
}
// driver program
public static void main (String[] args)
{
int matrix[][] = { { 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
{ 255, 255, 255, 255, 255, 255, 255, 255 },
482
Chapter 65. Discrete Cosine Transform (Algorithm and Program)
Output:
Source
https://www.geeksforgeeks.org/discrete-cosine-transform-algorithm-program/
483
Chapter 66
Input : N = 3, M = 4
mat[][] = {
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
}
Output : 3 2 1 0
2 1 0 0
1 0 0 1
C++
484
Chapter 66. Distance of nearest cell having 1 in a binary matrix
485
Chapter 66. Distance of nearest cell having 1 in a binary matrix
int mat[N][M] =
{
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
};
printDistance(mat);
return 0;
}
Java
486
Chapter 66. Distance of nearest cell having 1 in a binary matrix
Math.min(ans[i][j],
Math.abs(i-k)
+ Math.abs(j-l));
}
}
// Printing the answer.
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
System.out.print( ans[i][j] + " ");
System.out.println();
}
}
// Driven Program
public static void main (String[] args)
{
int mat[][] = { {0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 0} };
printDistance(mat);
}
}
// This code is contributed by anuj_67.
C#
487
Chapter 66. Distance of nearest cell having 1 in a binary matrix
PHP
488
Chapter 66. Distance of nearest cell having 1 in a binary matrix
<?php
// PHP program to find distance of nearest
// cell having 1 in a binary matrix.
$N = 3;
$M = 4;
// Print the distance of nearest cell
// having 1 for each cell.
function printDistance( $mat)
{
global $N,$M;
$ans = array(array());
// Initalize the answer
// matrix with INT_MAX.
for($i = 0; $i < $N; $i++)
for ( $j = 0; $j < $M; $j++)
$ans[$i][$j] = PHP_INT_MAX;
// For each cell
for ( $i = 0; $i < $N; $i++)
for ( $j = 0; $j < $M; $j++)
{
// Traversing the whole matrix
// to find the minimum distance.
for ($k = 0; $k < $N; $k++)
for ( $l = 0; $l < $M; $l++)
{
// If cell contain 1, check
// for minimum distance.
if ($mat[$k][$l] == 1)
$ans[$i][$j] = min($ans[$i][$j],
abs($i-$k) + abs($j - $l));
}
}
// Printing the answer.
for ( $i = 0; $i < $N; $i++)
{
for ( $j = 0; $j < $M; $j++)
echo $ans[$i][$j] , " ";
echo "\n";
}
}
489
Chapter 66. Distance of nearest cell having 1 in a binary matrix
Output:
3 2 1 0
2 1 0 0
1 0 0 1
1. Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to
store position and adjacent information.
2. Create an empty queue.
3. Traverse all matrix elements and insert positions of all 1s in queue.
4. Now do a BFS traversal of graph using above created queue. In BFS, we first explore
immediate adjacent of all 1’s, then adjacent of adjacent, and so on. Therefore we find
minimum distance.
490
Chapter 66. Distance of nearest cell having 1 in a binary matrix
{
private:
vector<int> g[MAX];
int n,m;
public:
graph(int a, int b)
{
n = a;
m = b;
}
// Function to create graph with N*M nodes
// considering each cell as a node and each
// boundry as an edge.
void createGraph()
{
int k = 1; // A number to be assigned to a cell
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
// If last row, then add edge on right side.
if (i == n)
{
// If not bottom right cell.
if (j != m)
{
g[k].push_back(k+1);
g[k+1].push_back(k);
}
}
// If last column, then add edge toward down.
else if (j == m)
{
g[k].push_back(k+m);
g[k+m].push_back(k);
}
// Else make edge in all four direction.
else
{
g[k].push_back(k+1);
g[k+1].push_back(k);
g[k].push_back(k+m);
g[k+m].push_back(k);
491
Chapter 66. Distance of nearest cell having 1 in a binary matrix
}
k++;
}
}
}
// BFS function to find minimum distance
void bfs(bool visit[], int dist[], queue<int> q)
{
while (!q.empty())
{
int temp = q.front();
q.pop();
for (int i = 0; i < g[temp].size(); i++)
{
if (visit[g[temp][i]] != 1)
{
dist[g[temp][i]] =
min(dist[g[temp][i]], dist[temp]+1);
q.push(g[temp][i]);
visit[g[temp][i]] = 1;
}
}
}
}
// Printing the solution.
void print(int dist[])
{
for (int i = 1, c = 1; i <= n*m; i++, c++)
{
cout << dist[i] << " ";
if (c%m == 0)
cout << endl;
}
}
};
// Find minimum distance
void findMinDistance(bool mat[N][M])
{
// Creating a graph with nodes values assigned
// from 1 to N x M and matrix adjacent.
graph g1(N, M);
492
Chapter 66. Distance of nearest cell having 1 in a binary matrix
g1.createGraph();
// To store minimum distance
int dist[MAX];
// To mark each node as visited or not in BFS
bool visit[MAX] = { 0 };
// Initalising the value of distance and visit.
for (int i = 1; i <= M*N; i++)
{
dist[i] = INT_MAX;
visit[i] = 0;
}
// Inserting nodes whose value in matrix
// is 1 in the queue.
int k = 1;
queue<int> q;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (mat[i][j] == 1)
{
dist[k] = 0;
visit[k] = 1;
q.push(k);
}
k++;
}
}
// Calling for Bfs with given Queue.
g1.bfs(visit, dist, q);
// Printing the solution.
g1.print(dist);
}
// Driven Progarm
int main()
{
bool mat[N][M] =
{
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
493
Chapter 66. Distance of nearest cell having 1 in a binary matrix
};
findMinDistance(mat);
return 0;
}
Output :
3 2 1 0
2 1 0 0
1 0 0 1
Source
https://www.geeksforgeeks.org/distance-nearest-cell-1-binary-matrix/
494
Chapter 67
495
Chapter 67. Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication)
diagram.
2) Calculate following values recursively. ae + bg, af + bh, ce + dg and cf + dh.
In the above method, we do 8 multiplications for matrices of size N/2 x N/2 and 4 additions.
Addition of two matrices takes O(N2 ) time. So the time complexity can be written as
Simple Divide and Conquer also leads to O(N3 ), can there be a better way?
In the above divide and conquer method, the main component for high time complexity is
8 recursive calls. The idea of Strassen’s method is to reduce the number of recursive
calls to 7. Strassen’s method is similar to above simple divide and conquer method in the
sense that this method also divide matrices to sub-matrices of size N/2 x N/2 as shown in
the above diagram, but in Strassen’s method, the four sub-matrices of result are calculated
using following formulae.
496
Chapter 67. Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication)
Generally Strassen’s Method is not preferred for practical applications for following reasons.
1) The constants used in Strassen’s method are high and for a typical application Naive
method works better.
2) For Sparse matrices, there are better methods especially designed for them.
3) The submatrices in recursion take extra space.
4) Because of the limited precision of computer arithmetic on noninteger values, larger
errors accumulate in Strassen’s algorithm than in Naive Method (Source: CLRS Book)
497
Chapter 67. Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication)
Source
https://www.geeksforgeeks.org/strassens-matrix-multiplication/
498
Chapter 68
Doolittle Algorithm : LU
Decomposition
Doolittle Algorithm :
499
Chapter 68. Doolittle Algorithm : LU Decomposition
It is always possible to factor a square matrix into a lower triangular matrix and an upper
triangular matrix. That is, [A] = [L][U]
Doolittle’s method provides an alternative way to factor A into an LU decomposition without
going through the hassle of Gaussian Elimination.
For a general n×n matrix A, we assume that an LU decomposition exists, and write the
form of L and U explicitly. We then systematically solve for the entries in L and U from
the equations that result from the multiplications necessary for A=LU.
Example :
Input :
Output :
C++
500
Chapter 68. Doolittle Algorithm : LU Decomposition
memset(upper, 0, sizeof(upper));
// Decomposing matrix into Upper and Lower
// triangular matrix
for (int i = 0; i < n; i++) {
// Upper Triangular
for (int k = i; k < n; k++) {
// Summation of L(i, j) * U(j, k)
int sum = 0;
for (int j = 0; j < i; j++)
sum += (lower[i][j] * upper[j][k]);
// Evaluating U(i, k)
upper[i][k] = mat[i][k] - sum;
}
// Lower Triangular
for (int k = i; k < n; k++) {
if (i == k)
lower[i][i] = 1; // Diagonal as 1
else {
// Summation of L(k, j) * U(j, i)
int sum = 0;
for (int j = 0; j < i; j++)
sum += (lower[k][j] * upper[j][i]);
// Evaluating L(k, i)
lower[k][i] = (mat[k][i] - sum) / upper[i][i];
}
}
}
// setw is for displaying nicely
cout << setw(6) << " Lower Triangular"
<< setw(32) << "Upper Triangular" << endl;
// Displaying the result :
for (int i = 0; i < n; i++) {
// Lower
for (int j = 0; j < n; j++)
cout << setw(6) << lower[i][j] << "\t";
cout << "\t";
// Upper
for (int j = 0; j < n; j++)
501
Chapter 68. Doolittle Algorithm : LU Decomposition
PHP
<?php
// PHP Program to decompose
// a matrix into lower and
// upper traingular matrix
$MAX = 100;
function luDecomposition($mat, $n)
{
$lower;
$upper;
for($i = 0; $i < $n; $i++)
for($j = 0; $j < $n; $j++)
{
$lower[$i][$j]= 0;
$upper[$i][$j]= 0;
}
// Decomposing matrix
// into Upper and Lower
// triangular matrix
for ($i = 0; $i < $n; $i++)
{
// Upper Triangular
for ($k = $i; $k < $n; $k++)
{
// Summation of
// L(i, j) * U(j, k)
$sum = 0;
for ($j = 0; $j < $i; $j++)
502
Chapter 68. Doolittle Algorithm : LU Decomposition
$sum += ($lower[$i][$j] *
$upper[$j][$k]);
// Evaluating U(i, k)
$upper[$i][$k] = $mat[$i][$k] - $sum;
}
// Lower Triangular
for ($k = $i; $k < $n; $k++)
{
if ($i == $k)
$lower[$i][$i] = 1; // Diagonal as 1
else
{
// Summation of L(k, j) * U(j, i)
$sum = 0;
for ($j = 0; $j < $i; $j++)
$sum += ($lower[$k][$j] *
$upper[$j][$i]);
// Evaluating L(k, i)
$lower[$k][$i] = (int)(($mat[$k][$i] -
$sum) / $upper[$i][$i]);
}
}
}
// setw is for
// displaying nicely
echo "\t\tLower Triangular";
echo "\t\t\tUpper Triangular\n";
// Displaying the result :
for ($i = 0; $i < $n; $i++)
{
// Lower
for ($j = 0; $j < $n; $j++)
echo "\t" . $lower[$i][$j] . "\t";
echo "\t";
// Upper
for ($j = 0; $j < $n; $j++)
echo $upper[$i][$j] . "\t";
echo "\n";
}
}
503
Chapter 68. Doolittle Algorithm : LU Decomposition
// Driver code
$mat = array(array(2, -1, -2),
array(-4, 6, 3),
array(-4, -2, 8));
luDecomposition($mat, 3);
// This code is contributed by mits
?>
Output:
Source
https://www.geeksforgeeks.org/doolittle-algorithm-lu-decomposition/
504
Chapter 69
505
Chapter 69. Easy way to remember Strassen’s Matrix Equation
• Write P1 = A; P2 = H; P3 = E; P4 = D
• For P5 we will use Diagonal Rule i.e.
(Sum the Diagonal Elements Of Matrix X ) * (Sum the Diagonal Elements Of Matrix
Y ), we get
P5 = (A + D)* (E + H)
• For P6 we will use Last CR Rule i.e. Last Column of X and Last Row of Y and
remember that Row+ and Column- so i.e. (B – D) * (G + H), we get
P6 = (B – D) * (G + H)
• For P7 we will use First CR Rule i.e. First Column of X and First Row of Y and
remember that Row+ and Column- so i.e. (A – C) * (E + F), we get
P6 = (A – C) * (E + F)
506
Chapter 69. Easy way to remember Strassen’s Matrix Equation
• Come Back to P1 : we have A there and it’s adjacent element in Y Matrix is E, since
Y is Column Matrix so we select a column in Y such that E won’t come, we find F H
Column, so multiply A with (F – H)
So, finally P1 = A * (F – H)
• Come Back to P2 : we have H there and it’s adjacent element in X Matrix is D, since
X is Row Matrix so we select a Row in X such that D won’t come, we find A B Column,
so multiply H with (A + B)
So, finally P2 = H * (A + B)
• Come Back to P3 : we have E there and it’s adjacent element in X Matrix is A, since X
is Row Matrix so we select a Row in X such that A won’t come, we find C D Column,
so multiply E with (C + D)
So, finally P3 = E * (C + D)
• Come Back to P4 : we have D there and it’s adjacent element in Y Matrix is H, since
Y is Column Matrix so we select a column in Y such that H won’t come, we find G E
Column, so multiply D with (G – E)
So, finally P4 = D * (G – E)
• Remember Counting : Write P1 + P2 at C2
• Write P3 + P4 at its diagonal Position i.e. at C3
• Write P4 + P5 + P6 at 1st position and subtract P2 i.e. C1 = P4 + P5 + P6 – P2
• Write odd values at last Position with alternating – and + sign i.e. P1 P3 P5 P7
becomes
C4 = P1 – P3 + P5 – P7
Improved By : BhavayAnand
Source
https://www.geeksforgeeks.org/easy-way-remember-strassens-matrix-equation/
507
Chapter 70
The primary diagonal is formed by the elements A00, A11, A22, A33.
Examples :
Input :
4
1 2 3 4
4 3 2 1
7 8 9 6
6 5 4 3
Output :
508
Chapter 70. Efficiently compute sums of diagonals of a matrix
Principal Diagonal: 16
Secondary Diagonal: 20
Input :
3
1 1 1
1 1 1
1 1 1
Output :
Principal Diagonal: 3
Secondary Diagonal: 3
Method 1 (O(n ^ 2) :
In this method we use two loops i.e. a loop for columns and a loop for rows and in the inner
loop we check for the condition stated above:
C++
509
Chapter 70. Efficiently compute sums of diagonals of a matrix
{ 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
printDiagonalSums(a, 4);
return 0;
}
Java
510
Chapter 70. Efficiently compute sums of diagonals of a matrix
printDiagonalSums(a, 4);
}
}
// This code is contributed by vt_m.
C#
511
Chapter 70. Efficiently compute sums of diagonals of a matrix
printDiagonalSums(a, 4);
}
}
// This code is contributed by vt_m.
PHP
<?php
// A simple PHP program to
// find sum of diagonals
$MAX = 100;
function printDiagonalSums($mat, $n)
{
global $MAX;
$principal = 0;
$secondary = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// Condition for
// principal diagonal
if ($i == $j)
$principal += $mat[$i][$j];
// Condition for
// secondary diagonal
if (($i + $j) == ($n - 1))
$secondary += $mat[$i][$j];
}
}
echo "Principal Diagonal:" ,
$principal ,"\n";
echo "Secondary Diagonal:",
$secondary ,"\n";
}
// Driver code
$a = array (array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ),
array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ));
printDiagonalSums($a, 4);
512
Chapter 70. Efficiently compute sums of diagonals of a matrix
Output:
Principal Diagonal:18
Secondary Diagonal:18
Method 2 (O(n) :
In this method we use one loop i.e. a loop for calculating sum of both the principal and
secondary diagonals:
C++
Java
513
Chapter 70. Efficiently compute sums of diagonals of a matrix
C#
514
Chapter 70. Efficiently compute sums of diagonals of a matrix
PHP
<?php
// An efficient PHP program
// to find sum of diagonals
$MAX = 100;
function printDiagonalSums($mat, $n)
{
global $MAX;
$principal = 0; $secondary = 0;
for ($i = 0; $i < $n; $i++)
{
$principal += $mat[$i][$i];
$secondary += $mat[$i][$n - $i - 1];
}
echo "Principal Diagonal:" ,
$principal ,"\n";
echo "Secondary Diagonal:" ,
$secondary ,"\n";
}
515
Chapter 70. Efficiently compute sums of diagonals of a matrix
// Driver Code
$a = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(1, 2, 3, 4),
array(5, 6, 7, 8));
printDiagonalSums($a, 4);
// This code is contributed by aj_36
?>
Output :
Principal Diagonal:18
Secondary Diagonal:18
Source
https://www.geeksforgeeks.org/efficiently-compute-sums-of-diagonals-of-a-matrix/
516
Chapter 71
1. Count cup, cdown, cleft and cright for U(Up), D(Down), L(Left) and R(Right) move-
ments respectively.
2. Calculate final_x = x + (cright – cleft) and final_y = y + (cdown – cup).
517
Chapter 71. Final cell position in the matrix
#include <bits/stdc++.h>
using namespace std;
// function to find the final cell position
// in the given matrix
void finalPos(char command[], int n,
int x, int y)
{
// to count up, down, left and cright
// movements
int cup, cdown, cleft, cright;
// to store the final coordinate position
int final_x, final_y;
cup = cdown = cleft = cright = 0;
// traverse the command array
for (int i = 0; i < n; i++) {
if (command[i] == 'U')
cup++;
else if (command[i] == 'D')
cdown++;
else if (command[i] == 'L')
cleft++;
else if (command[i] == 'R')
cright++;
}
// calculate final values
final_x = x + (cright - cleft);
final_y = y + (cdown - cup);
cout << "Final Position: "
<< "("
<< final_x << ", " << final_y << ")";
}
// Driver program to test above
int main()
{
char command[] = "DDLRULL";
int n = (sizeof(command) / sizeof(char)) - 1;
int x = 3, y = 4;
finalPos(command, n, x, y);
return 0;
}
518
Chapter 71. Final cell position in the matrix
Java
519
Chapter 71. Final cell position in the matrix
// Driver Code
public static void main(String []args)
{
String command = "DDLRULL";
int n = command.length();
int x = 3, y = 4;
finalPos(command, n, x, y);
}
}
// This code is contributed
// by Subhadeep
Output:
Source
https://www.geeksforgeeks.org/final-cell-position-in-the-matrix/
520
Chapter 72
Now you are given n, and you have to find out nth term using above formula.
Examples:
Input : n = 2
Output : 5
Input : n = 3
Output :13
Prerequisite :
Basic Approach:This problem can be solved by simply just iterating over the n terms.
Every time you find a term, using this term find next one and so on. But time complexity
of this problem is of order O(n).
Optimized Approach
All such problem where a term is a function of other terms in linear fashion. Then these
can be solved using Matrix (Please refer : Matrix Exponentiation). First we make transfor-
mation matrix and then just use matrix exponentiation to find Nth term.
521
Chapter 72. Find Nth term (A matrix exponentiation example)
522
Chapter 72. Find Nth term (A matrix exponentiation example)
{
if (n <= 1)
return 1;
// This power function returns first row of
// {Transformation Matrix}^n-1*Initial Vector
n--;
// This is an identity matrix.
ll res[2][2] = { 1, 0, 0, 1 };
// this is Transformation matrix.
ll tMat[2][2] = { 2, 3, 1, 0 };
// Matrix exponentiation to calculate power of {tMat}^n-1
// store res in "res" matrix.
while (n) {
if (n & 1) {
ll tmp[2][2];
tmp[0][0] = (res[0][0] * tMat[0][0] +
res[0][1] * tMat[1][0]) % MOD;
tmp[0][1] = (res[0][0] * tMat[0][1] +
res[0][1] * tMat[1][1]) % MOD;
tmp[1][0] = (res[1][0] * tMat[0][0] +
res[1][1] * tMat[1][0]) % MOD;
tmp[1][1] = (res[1][0] * tMat[0][1] +
res[1][1] * tMat[1][1]) % MOD;
res[0][0] = tmp[0][0];
res[0][1] = tmp[0][1];
res[1][0] = tmp[1][0];
res[1][1] = tmp[1][1];
}
n = n / 2;
ll tmp[2][2];
tmp[0][0] = (tMat[0][0] * tMat[0][0] +
tMat[0][1] * tMat[1][0]) % MOD;
tmp[0][1] = (tMat[0][0] * tMat[0][1] +
tMat[0][1] * tMat[1][1]) % MOD;
tmp[1][0] = (tMat[1][0] * tMat[0][0] +
tMat[1][1] * tMat[1][0]) % MOD;
tmp[1][1] = (tMat[1][0] * tMat[0][1] +
tMat[1][1] * tMat[1][1]) % MOD;
tMat[0][0] = tmp[0][0];
tMat[0][1] = tmp[0][1];
tMat[1][0] = tmp[1][0];
tMat[1][1] = tmp[1][1];
}
523
Chapter 72. Find Nth term (A matrix exponentiation example)
// res store {Transformation matrix}^n-1
// hence will be first row of res*Initial Vector.
return (res[0][0] * 1 + res[0][1] * 1) % MOD;
}
// Driver code
int main()
{
ll n = 3;
cout << power(n);
return 0;
}
Output:
13
Source
https://www.geeksforgeeks.org/find-nth-term-a-matrix-exponentiation-example/
524
Chapter 73
Input:
O O O O G
O W W O O
O O O W O
G W W W O
O O O O G
Output:
3 3 2 1 0
2 -1 -1 2 1
1 2 3 -1 2
0 -1 -1 -1 1
1 2 2 1 0
525
Chapter 73. Find Shortest distance from a guard in a Bank
The idea is to do BFS. We first enqueue all cells containing the guards and loop till queue
is not empty. For each iteration of the loop, we dequeue the front cell from the queue and
for each of its four adjacent cells, if cell is an open area and its distance from guard is not
calculated yet, we update its distance and enqueue it. Finally after BFS procedure is over,
we print the distance matrix.
Below is C++ implementation of above idea –
526
Chapter 73. Find Shortest distance from a guard in a Bank
}
// Function to replace all of the O's in the matrix
// with their shortest distance from a guard
void findDistance(char matrix[][N])
{
int output[M][N];
queue<queueNode> q;
// finding Guards location and adding into queue
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
// initialize each cell as -1
output[i][j] = -1;
if (matrix[i][j] == 'G')
{
queueNode pos = {i, j, 0};
q.push(pos);
// guard has 0 distance
output[i][j] = 0;
}
}
}
// do till queue is empty
while (!q.empty())
{
// get the front cell in the queue and update
// its adjacent cells
queueNode curr = q.front();
int x = curr.i, y = curr.j, dist = curr.distance;
// do for each adjacent cell
for (int i = 0; i < 4; i++)
{
// if adjacent cell is valid, has path and
// not visited yet, en-queue it.
if (isSafe(x + row[i], y + col[i], matrix, output)
&& isValid(x + row[i], y + col[i]))
{
output[x + row[i]][y + col[i]] = dist + 1;
queueNode pos = {x + row[i], y + col[i], dist + 1};
q.push(pos);
}
}
527
Chapter 73. Find Shortest distance from a guard in a Bank
// dequeue the front cell as its distance is found
q.pop();
}
// print output matrix
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
cout << std::setw(3) << output[i][j];
cout << endl;
}
}
// Driver code
int main()
{
char matrix[][N] =
{
{'O', 'O', 'O', 'O', 'G'},
{'O', 'W', 'W', 'O', 'O'},
{'O', 'O', 'O', 'W', 'O'},
{'G', 'W', 'W', 'W', 'O'},
{'O', 'O', 'O', 'O', 'G'}
};
findDistance(matrix);
return 0;
}
Output:
3 3 2 1 0
2 -1 -1 2 1
1 2 3 -1 2
0 -1 -1 -1 1
1 2 2 1 0
Source
https://www.geeksforgeeks.org/find-shortest-distance-guard-bank/
528
Chapter 74
Find a common element in all rows of a given row-wise sorted matrix - GeeksforGeeks
Given a matrix where every row is sorted in increasing order. Write a function that finds
and returns a common element in all rows. If there is no common element, then returns -1.
Example:
A O(m*n*n) simple solution is to take every element of first row and search it in all other
rows, till we find a common element. Time complexity of this solution is O(m*n*n) where
m is number of rows and n is number of columns in given matrix. This can be improved to
O(m*n*Logn) if we use Binary Search instead of linear search.
We can solve this problem in O(mn) time using the approach similar to merge of Merge
Sort. The idea is to start from the last column of every row. If elements at all last columns
are same, then we found the common element. Otherwise we find the minimum of all last
columns. Once we find a minimum element, we know that all other elements in last columns
cannot be a common element, so we reduce last column index for all rows except for the row
which has minimum value. We keep repeating these steps till either all elements at current
last column don’t become same, or a last column index reaches 0.
Below is the implementation of above idea.
529
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
530
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
if (column[i] == 0)
return -1;
column[i] -= 1; // Reduce last column index by 1
}
else
eq_count++;
}
// If equal count becomes M, return the value
if (eq_count == M)
return mat[min_row][column[min_row]];
}
return -1;
}
// driver program to test above function
int main()
{
int mat[M][N] = { {1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9},
};
int result = findCommon(mat);
if (result == -1)
printf("No common element");
else
printf("Common element is %d", result);
return 0;
}
Java
531
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
532
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
}
// If equal count becomes M,
// return the value
if (eq_count == M)
return mat[min_row][column[min_row]];
}
return -1;
}
// Driver code
public static void main (String[] args)
{
int mat[][] = { {1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9}};
int result = findCommon(mat);
if (result == -1)
System.out.print("No common element");
else
System.out.print("Common element is "+ result);
}
}
// This code is contributed by Anant Agarwal.
C#
533
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
534
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
if (column[i] == 0)
return -1;
// Reduce last column index
// by 1
column[i] -= 1;
}
else
eq_count++;
}
// If equal count becomes M,
// return the value
if (eq_count == M)
return mat[min_row,
column[min_row]];
}
return -1;
}
// Driver code
public static void Main ()
{
int [,]mat = { {1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9} };
int result = findCommon(mat);
if (result == -1)
Console.Write("No common element");
else
Console.Write("Common element is "
+ result);
}
}
// This code is contributed by Sam007.
Output:
Common element is 5
535
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
Step2:
For i = 1 to M-1
For j = 0 to N-1
If (mat[i][j] is already present in Hash Table)
If (And this is not a repetition in current row.
This can be checked by comparing HashTable value with
row number)
Update the value of this key in HashTable with current
row number
Step3: Iterate over HashTable and print all those keys for
which value = M
536
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix
Time complexity of the above hashing based solution is O(MN) under the assumption that
search and insert in HashTable take O(1) time. Thanks to Nishant for suggesting this
solution in a comment below.
Exercise: Given n sorted arrays of size m each, find all common elements in all arrays in
O(mn) time.
This article is contributed by Anand Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/find-common-element-rows-row-wise-sorted-matrix/
537
Chapter 75
Input : 10 20 15
21 30 14
7 16 32
Output : 30
30 is a peak element because all its
neighbors are smaller or equal to it.
32 can also be picked as a peak.
Input : 10 7
11 17
Output : 17
538
Chapter 75. Find a peak element in a 2D array
539
Chapter 75. Find a peak element in a 2D array
// If we are on the first or last column,
// max is a peak
if (mid == 0 || mid == columns-1)
return max;
// If mid column maximum is also peak
if (max >= arr[max_index][mid-1] &&
max >= arr[max_index][mid+1])
return max;
// If max is less than its left
if (max < arr[max_index][mid-1])
return findPeakRec(arr, rows, columns, mid - mid/2);
// If max is less than its left
// if (max < arr[max_index][mid+1])
return findPeakRec(arr, rows, columns, mid+mid/2);
}
// A wrapper over findPeakRec()
int findPeak(int arr[][MAX], int rows, int columns)
{
return findPeakRec(arr, rows, columns, columns/2);
}
// Driver Code
int main()
{
int arr[][MAX] = {{ 10, 8, 10, 10 },
{ 14, 13, 12, 11 },
{ 15, 9, 11, 21 },
{ 16, 17, 19, 20 } };
// Number of Columns
int rows = 4, columns = 4;
cout << findPeak(arr, rows, columns);
return 0;
}
Output: 21
Time Complexity : O(rows * log(columns)). We recur for half number of columns. In every
recursive call we linearly search for maximum in current mid column.
Auxiliary Space : O(columns/2) for Recursion Call Stack
Source:
540
Chapter 75. Find a peak element in a 2D array
https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-201
lecture-videos/MIT6_006F11_lec01.pdf
Source
https://www.geeksforgeeks.org/find-peak-element-2d-array/
541
Chapter 76
Input:
mat[N][N] = {{ 1, 2, -1, -4, -20 },
{ -8, -3, 4, 2, 1 },
{ 3, 8, 6, 1, 3 },
{ -4, -1, 1, 7, -6 },
{ 0, -4, 10, -5, 1 }};
Output: 18
The maximum value is 18 as mat[4][2]
- mat[1][0] = 18 has maximum difference.
The program should do only ONE traversal of the matrix. i.e. expected time complexity is
O(n2 )
A simple solution would be to apply Brute-Force. For all values mat(a, b) in the matrix,
we find mat(c, d) that has maximum value such that c > a and d > b and keeps on updating
maximum value found so far. We finally return the maximum value.
Below is its implementation.
C++
542
Chapter 76. Find a specific pair in Matrix
#define N 5
// The function returns maximum value A(d,e) - A(a,b)
// over all choices of indexes such that both d > a
// and e > b.
int findMaxValue(int mat[][N])
{
// stores maximum value
int maxValue = INT_MIN;
// Consider all possible pairs mat[a][b] and
// mat[d][e]
for (int a = 0; a < N - 1; a++)
for (int b = 0; b < N - 1; b++)
for (int d = a + 1; d < N; d++)
for (int e = b + 1; e < N; e++)
if (maxValue < (mat[d][e] - mat[a][b]))
maxValue = mat[d][e] - mat[a][b];
return maxValue;
}
// Driver program to test above function
int main()
{
int mat[N][N] = {
{ 1, 2, -1, -4, -20 },
{ -8, -3, 4, 2, 1 },
{ 3, 8, 6, 1, 3 },
{ -4, -1, 1, 7, -6 },
{ 0, -4, 10, -5, 1 }
};
cout << "Maximum Value is "
<< findMaxValue(mat);
return 0;
}
Java
543
Chapter 76. Find a specific pair in Matrix
Python 3
544
Chapter 76. Find a specific pair in Matrix
C#
545
Chapter 76. Find a specific pair in Matrix
PHP
<?php
// A Naive method to find maximum
// value of $mat[d][e] - ma[a][b]
// such that $d > $a and $e > $b
$N = 5;
// The function returns maximum
546
Chapter 76. Find a specific pair in Matrix
Output:
Maximum Value is 18
The above program runs in O(n^4) time which is nowhere close to expected time complexity
of O(n^2)
An efficient solution uses extra space. We pre-process the matrix such that index(i, j)
stores max of elements in matrix from (i, j) to (N-1, N-1) and in the process keeps on
updating maximum value found so far. We finally return the maximum value.
547
Chapter 76. Find a specific pair in Matrix
C++
548
Chapter 76. Find a specific pair in Matrix
Java
549
Chapter 76. Find a specific pair in Matrix
550
Chapter 76. Find a specific pair in Matrix
int mat[][] = {
{ 1, 2, -1, -4, -20 },
{ -8, -3, 4, 2, 1 },
{ 3, 8, 6, 1, 3 },
{ -4, -1, 1, 7, -6 },
{ 0, -4, 10, -5, 1 }
};
System.out.print("Maximum Value is " +
findMaxValue(N,mat));
}
}
// Contributed by Prakriti Gupta
C#
551
Chapter 76. Find a specific pair in Matrix
552
Chapter 76. Find a specific pair in Matrix
{ 3, 8, 6, 1, 3 },
{ -4, -1, 1, 7, -6 },
{ 0, -4, 10, -5, 1 }};
Console.Write("Maximum Value is " +
findMaxValue(N,mat));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// An efficient method to find
// maximum value of mat[d] - ma[a][b]
// such that c > a and d > b
$N = 5;
// The function returns maximum
// value A(c,d) - A(a,b) over
// all choices of indexes such
// that both c > a and d > b.
function findMaxValue($mat)
{
global $N;
// stores maximum value
$maxValue = PHP_INT_MIN;
// maxArr[i][j] stores max
// of elements in matrix
// from (i, j) to (N-1, N-1)
$maxArr[$N][$N] = array();
// last element of maxArr
// will be same's as of
// the input matrix
$maxArr[$N - 1][$N - 1] = $mat[$N - 1][$N - 1];
// preprocess last row
$maxv = $mat[$N - 1][$N - 1]; // Initialize max
for ($j = $N - 2; $j >= 0; $j--)
{
if ($mat[$N - 1][$j] > $maxv)
$maxv = $mat[$N - 1][$j];
$maxArr[$N - 1][$j] = $maxv;
}
553
Chapter 76. Find a specific pair in Matrix
Output:
Maximum Value is 18
554
Chapter 76. Find a specific pair in Matrix
If we are allowed to modify of the matrix, we can avoid using extra space and use input
matrix instead.
Exercise: Print index (a, b) and (c, d) as well.
Improved By : nitin mittal, ChitraNayal
Source
https://www.geeksforgeeks.org/find-a-specific-pair-in-matrix/
555
Chapter 77
A simple solution is to one by one sort all rows and check all rows. If any row is completely
equal to given row that means current row is a permutation of given row. Time complexity
for this approach will be O(m*n log n).
An efficient approach is to use a hashing. Simply create a hash set for given row. After
hash set creation, traverse through remaining rows and for every row check if all of its
elements are present in hash set or not.
CPP
556
Chapter 77. Find all permuted rows of a given row in a matrix
Python3
557
Chapter 77. Find all permuted rows of a given row in a matrix
558
Chapter 77. Find all permuted rows of a given row in a matrix
permutatedRows(mat, m, n, r)
# This code is contributed
# by Upendra Singh Bartwal.
Output:
0, 2
CPP
Output:
0, 2
559
Chapter 77. Find all permuted rows of a given row in a matrix
Exercise :
Extend the above solution to work for input matrix where all elements of a row don’t have
be distinct. (Hit : We can use Hash Map instead of Hash Set)
Improved By : banavath santhosh
Source
https://www.geeksforgeeks.org/find-permuted-rows-given-row-matrix/
560
Chapter 78
input = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]
]
Output:
[
[2, 3, 3, 5], [3, 1, 5, 1], [5, 3, 6, 5]
]
Explanation:
We have three rectangles here, starting from
(2, 3), (3, 1), (5, 3)
Input = [
[1, 0, 1, 1, 1, 1, 1],
561
Chapter 78. Find all rectangles filled with 0
[1, 1, 0, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1, 0]
]
Output:
[
[0, 1, 0, 1], [1, 2, 1, 2], [2, 3, 3, 5],
[3, 1, 4, 1], [5, 3, 5, 6], [7, 2, 7, 2],
[7, 6, 7, 6]
]
562
Chapter 78. Find all rectangles filled with 0
563
Chapter 78. Find all rectangles filled with 0
if a[i][j] == 0:
# storing initial position
# of rectangle
output.append([i, j])
# will be used for the
# last position
index = index + 1
findend(i, j, a, output, index)
print (output)
# driver code
tests = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1]
]
get_rectangle_coordinates(tests)
Output:
Asked in Intuit
Source
https://www.geeksforgeeks.org/find-rectangles-filled-0/
564
Chapter 79
Input : mat[][] = 11 2 4
4 5 6
10 8 -12
Output : 15
Sum of primary diagonal = 11 + 5 + (-12) = 4.
Sum of primary diagonal = 4 + 5 + 10 = 19.
Difference = |19 - 4| = 15.
Input : mat[][] = 10 2
4 5
Output : 7
Calculate the sums across the two diagonals of a square matrix. Along the first diagonal of
the matrix, row index = column index i.e mat[i][j] lies on the first diagonal if i = j. Along
the other diagonal, row index = n – 1 – column index i.e mat[i][j] lies on the second diagonal
if i = n-1-j. By using two loops we traverse the entire matrix and calculate the sum across
the diagonals of the matrix.
Below is the implementation of this approach:
C++
565
Chapter 79. Find difference between sums of two diagonals
Java
566
Chapter 79. Find difference between sums of two diagonals
C#
567
Chapter 79. Find difference between sums of two diagonals
568
Chapter 79. Find difference between sums of two diagonals
// This code is contributed by shiv_bhakt.
PHP
<?php
// PHP program to find the difference
// between the sum of diagonal.
function difference($arr, $n)
{
// Initialize sums of diagonals
$d1 = 0; $d2 = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// finding sum of
// primary diagonal
if ($i == $j)
$d1 += $arr[$i][$j];
// finding sum of
// secondary diagonal
if ($i == $n - $j - 1)
$d2 += $arr[$i][$j];
}
}
// Absolute difference of the sums
// across the diagonals
return abs($d1 - $d2);
}
// Driver Code
{
$n = 3;
$arr = array(array(11, 2, 4),
array(4 , 5, 6),
array(10, 8, -12));
echo difference($arr, $n);
return 0;
}
569
Chapter 79. Find difference between sums of two diagonals
// This code is contributed by nitin mittal.
?>
Output:
15
C++
570
Chapter 79. Find difference between sums of two diagonals
};
cout << difference(arr, n);
return 0;
}
Java
C#
571
Chapter 79. Find difference between sums of two diagonals
PHP
<?php
// PHP program to find the difference
// between the sum of diagonal.
572
Chapter 79. Find difference between sums of two diagonals
function difference($arr, $n)
{
// Initialize sums of diagonals
$d1 = 0; $d2 = 0;
for ($i = 0; $i < $n; $i++)
{
$d1 += $arr[$i][$i];
$d2 += $arr[$i][$n-$i-1];
}
// Absolute difference of the sums
// across the diagonals
return abs($d1 - $d2);
}
// Driver Code
{
$n = 3;
$arr =array(array(11, 2, 4),
array(4, 5, 6),
array(10, 8, -12));
echo difference($arr, $n);
return 0;
}
// This code is contributed by nitin mittal.
?>
Output:
15
Source
https://www.geeksforgeeks.org/find-difference-between-sums-of-two-diagonals/
573
Chapter 80
Method 1: Using three nested loops. Check if an element of 1st row is present in all the
subsequent rows. Time Complexity of O(n3 ). Extra space could be required to handle the
duplicate elements.
Method 2: Sort all the rows of the matrix individually in increasing order. Then apply a
modified approach of the problem of finding common elements in 3 sorted arrays. Below
an implementation for the same is given.
574
Chapter 80. Find distinct elements common to all rows of a matrix
C++
575
Chapter 80. Find distinct elements common to all rows of a matrix
curr_index[i]++;
// if the element was not present at the column
// before to the 'curr_index' of the row
if (mat[i][curr_index[i]-1] != value)
present = false;
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
cout << value << " ";
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
// Driver program to test above
int main()
{
int mat[][MAX] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
return 0;
}
Java
576
Chapter 80. Find distinct elements common to all rows of a matrix
class GFG {
// function to individually sort
// each row in increasing order
public static void sortRows(int mat[][], int n)
{
for (int i=0; i<n; i++)
Arrays.sort(mat[i]);
}
// function to find all the common elements
public static void findAndPrintCommonElements(int mat[][],
int n)
{
// sort rows individually
sortRows(mat, n);
// current column index of each row is stored
// from where the element is being searched in
// that row
int curr_index[] = new int[n];
int f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
// value present at the current column index
// of 1st row
int value = mat[0][curr_index[0]];
boolean present = true;
// 'value' is being searched in all the
// subsequent rows
for (int i=1; i<n; i++)
{
// iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
// if the element was not present at the
// column before to the 'curr_index' of the
// row
577
Chapter 80. Find distinct elements common to all rows of a matrix
Output:
1 3 14
Time Complexity: O(n2 log n), each row of size n requires O(nlogn) for sorting and there
are total n rows.
Auxiliary Space : O(n) to store current column indexes for each row.
578
Chapter 80. Find distinct elements common to all rows of a matrix
579
Chapter 80. Find distinct elements common to all rows of a matrix
us.erase(*itr);
// if size of 'us' becomes 0,
// then there are no common elements
if (us.size() == 0)
break;
}
// print the common elements
unordered_set<int>:: iterator itr;
for (itr=us.begin(); itr!=us.end(); itr++)
cout << *itr << " ";
}
// Driver program to test above
int main()
{
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
return 0;
}
Output:
3 2
Source
https://www.geeksforgeeks.org/find-distinct-elements-common-rows-matrix/
580
Chapter 81
Output :
There is a duplicate row at position: 4
There is a duplicate row at position: 5
There is a duplicate row at position: 6
581
Chapter 81. Find duplicate rows in a binary matrix
The solution approach towards the question is to first insert the matrix in the binary trie
and then if the new added row is already present in the trie then we will now that it is a
duplicate row
582
Chapter 81. Find duplicate rows in a binary matrix
Output:
Another approach without using Trie but does not work for large number of
columns
Another approach is be to convert the decimal equivalent of row and check if a new row has
the same decimal equivalent then it is a duplicate row. It will not work if the number of
columns is large .
Source
https://www.geeksforgeeks.org/find-duplicate-rows-binary-matrix/
583
Chapter 82
584
Chapter 82. Find floor and ceil in an unsorted array
2) Use binary search to find floor and ceiling of x. Refer this and this for implementation
of floor and ceiling in a sorted array.
Time Complexity : O(n log n)
Auxiliary Space : O(1)
This solution is works well if there are multiple queries of floor and ceiling on a static array.
We can sort the array once and answer the queries in O(Log n) time.
C/C++
585
Chapter 82. Find floor and ceil in an unsorted array
}
if (fDist == INT_MAX)
cout << "Floor doesn't exist " << endl;
else
cout << "Floor is " << arr[fInd] << endl;
if (cDist == INT_MAX)
cout << "Ceil doesn't exist " << endl;
else
cout << "Ceil is " << arr[cInd] << endl;
}
// Driver code
int main()
{
int arr[] = {5, 6, 8, 9, 6, 5, 5, 6};
int n = sizeof(arr)/sizeof(int);
int x = 7;
floorAndCeil(arr, n, x);
return 0;
}
Java
586
Chapter 82. Find floor and ceil in an unsorted array
cInd = i;
cDist = arr[i] - x;
}
// If current element is closer than
// previous floor.
if (arr[i] <= x && fDist > (x - arr[i]))
{
fInd = i;
fDist = x - arr[i];
}
}
if(fDist == Integer.MAX_VALUE)
System.out.println("Floor doesn't exist " );
else
System.out.println("Floor is " + arr[fInd]);
if(cDist == Integer.MAX_VALUE)
System.out.println("Ceil doesn't exist ");
else
System.out.println("Ceil is " + arr[cInd]);
}
public static void main (String[] args)
{
int arr[] = {5, 6, 8, 9, 6, 5, 5, 6};
int x = 7;
floorAndCeil(arr, x);
}
}
C#
587
Chapter 82. Find floor and ceil in an unsorted array
PHP
588
Chapter 82. Find floor and ceil in an unsorted array
<?php
// PHP program to find
// floor and ceiling in
// an unsorted array.
// Function to floor and
// ceiling of x in arr[]
function floorAndCeil($arr,
$n, $x)
{
// Indexes of floor
// and ceiling
$fInd = 0;
$cInd = 0;
// Distances of current
// floor and ceiling
$fDist = 999999;
$cDist = 999999;
for ($i = 0; $i < $n; $i++)
{
// If current element
// is closer than
// previous ceiling.
if ($arr[$i] >= $x &&
$cDist > ($arr[$i] - $x))
{
$cInd = $i;
$cDist = $arr[$i] - $x;
}
// If current element
// is closer than
// previous floor.
if ($arr[$i] <= $x &&
$fDist > ($x - $arr[$i]))
{
$fInd = $i;
$fDist = $x - $arr[$i];
}
}
if ($fDist == 999999)
echo "Floor doesn't ".
"exist " . "\n" ;
else
echo "Floor is " .
589
Chapter 82. Find floor and ceil in an unsorted array
$arr[$fInd] . "\n";
if ($cDist == 999999)
echo "Ceil doesn't " .
"exist " . "\n";
else
echo "Ceil is " .
$arr[$cInd] . "\n";
}
// Driver code
$arr = array(5, 6, 8, 9,
6, 5, 5, 6);
$n = count($arr);
$x = 7;
floorAndCeil($arr, $n, $x);
// This code is contributed
// by Sam007
?>
Output :
Floor is 6
Ceil is 8
Source
https://www.geeksforgeeks.org/find-floor-ceil-unsorted-array/
590
Chapter 83
Find if a 2-D array is completely traversed or not by following the cell values - GeeksforGeeks
You are given a 2-D array. We have to traverse each and every cell of given array by
following the cell locations then return true else false. The value of each cell is given by (x,
y) where (x, y) is also shows next following cells position. Eg. (0, 0) shows starting cell.
And ‘null’ shows our final destination after traversing every cell.
Examples:
591
Chapter 83. Find if a 2-D array is completely traversed or not by following the cell values
Input : { 0, 1 1, 2 1, 1
0, 2 2, 0 2, 1
0, 0 1, 0 null }
Output : false
Input : { 0, 1 2, 0
null 1, 0
2, 1 1, 1 }
Output : true
We take a visited array if we visit a cell then make its value true in visited array, so that we
can capture the cycle in our grid for next time when we visit it again. And if we find null
before completing the loop then it means we didn’t traversed all the cell of given array.
592
Chapter 83. Find if a 2-D array is completely traversed or not by following the cell values
Output:
true
593
Chapter 83. Find if a 2-D array is completely traversed or not by following the cell values
Source
https://www.geeksforgeeks.org/find-2-d-array-completely-traversed-not-following-cell-values/
594
Chapter 84
Examples :
Input: mat[N][N] = {{ 6, 7, 8, 9 },
{ 4, 6, 7, 8 },
{ 1, 4, 6, 7 },
{ 0, 1, 4, 6 },
{ 2, 0, 1, 4 }};
Output : True;
595
Chapter 84. Find if given matrix is Toeplitz or not
The idea is very simple. For each element of first row and first column(or last row and last
column) in the matrix, we check if descending diagonal starting from that element have
same values or not. If we found any diagonal having different values, we return false.
C++
596
Chapter 84. Find if given matrix is Toeplitz or not
Java
597
Chapter 84. Find if given matrix is Toeplitz or not
598
Chapter 84. Find if given matrix is Toeplitz or not
Python3
599
Chapter 84. Find if given matrix is Toeplitz or not
C#
600
Chapter 84. Find if given matrix is Toeplitz or not
601
Chapter 84. Find if given matrix is Toeplitz or not
if (isToepliz(mat))
Console.WriteLine("Matrix is a Toepliz ");
else
Console.WriteLine("Matrix is not a Toepliz ");
}
}
// This code is contributed by KRV.
PHP
<?php
// PHP program to check whether
// given matrix is a Toeplitz
// matrix or not
// Function to check if all
// elements present in descending
// diagonal starting from position
// (i, j) in the matrix are all
// same or not
function checkDiagonal($mat, $i, $j)
{
$N = 5; $M = 4;
$res = $mat[$i][$j];
while (++$i < $N && ++$j < $M)
{
// mismatch found
if ($mat[$i][$j] != $res)
return false;
}
// we only reach here when
// all elements in given
// diagonal are same
return true;
}
// Function to check whether
// given matrix is a
// Toeplitz matrix or not
function isToepliz($mat)
{
$N = 5; $M = 4;
// do for each element in first row
for ($i = 0; $i < $M; $i++)
{
602
Chapter 84. Find if given matrix is Toeplitz or not
Output :
Matrix is a Toepliz
The time complexity of this solution would be O(n2 ) as we are traversing each element
in the matrix once only.
603
Chapter 84. Find if given matrix is Toeplitz or not
Reference: https://en.wikipedia.org/wiki/Toeplitz_matrix
Improved By : KRV, nitin mittal
Source
https://www.geeksforgeeks.org/find-if-given-matrix-is-toeplitz-or-not/
604
Chapter 85
Input :
mat[][] = { 1 0 0 1 0
0 0 1 0 1
0 0 0 1 0
1 0 1 0 1}
Output : Yes
as there exists-
1 0 1
0 1 0
1 0 1
for i = 1 to rows
for j = 1 to columns
if matrix[i][j] == 1
for k=i+1 to rows
605
Chapter 85. Find if there is a rectangle in binary matrix with corners as 1
606
Chapter 85. Find if there is a rectangle in binary matrix with corners as 1
Output:
Yes
Efficient Approach
– Scan from top to down, line by line
– For each line, remember each combination of 2 1’s and push that into a hash-set
– If we ever find that combination again in a later line, we get our rectangle
– Time Complexity of this solution- O(n*m^2)
607
Chapter 85. Find if there is a rectangle in binary matrix with corners as 1
Output:
Yes
Improved By : abhishekahuja02
Source
https://www.geeksforgeeks.org/find-rectangle-binary-matrix-corners-1/
608
Chapter 86
Find length of the longest consecutive path from a given starting character - GeeksforGeeks
Given a matrix of characters. Find length of the longest path from a given character, such
that all characters in the path are consecutive to each other, i.e., every character in path is
next to previous in alphabetical order. It is allowed to move in all 8 directions from a cell.
Example
609
Chapter 86. Find length of the longest consecutive path from a given starting character
Output: 5
If starting point is 'e', then longest path with consecutive
characters is "e f g h i".
Output: 1
'c' is not present in all adjacent cells of 'b'
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to first search given starting character in the given matrix. Do Depth First
Search (DFS) from all occurrences to find all consecutive paths. While doing DFS, we may
encounter many subproblems again and again. So we use dynamic programming to store
results of subproblems.
Below is the implementation of above idea.
C++
610
Chapter 86. Find length of the longest consecutive path from a given starting character
return false;
return true;
}
// Check whether current character is adjacent to previous
// character (character processed in parent call) or not.
bool isadjacent(char prev, char curr)
{
return ((curr - prev) == 1);
}
// i, j are the indices of the current cell and prev is the
// character processed in the parent call.. also mat[i][j]
// is our current character.
int getLenUtil(char mat[R][C], int i, int j, char prev)
{
// If this cell is not valid or current character is not
// adjacent to previous one (e.g. d is not adjacent to b )
// or if this cell is already included in the path than return 0.
if (!isvalid(i, j) || !isadjacent(prev, mat[i][j]))
return 0;
// If this subproblem is already solved , return the answer
if (dp[i][j] != -1)
return dp[i][j];
int ans = 0; // Initialize answer
// recur for paths with differnt adjacent cells and store
// the length of longest path.
for (int k=0; k<8; k++)
ans = max(ans, 1 + getLenUtil(mat, i + x[k],
j + y[k], mat[i][j]));
// save the answer and return
return dp[i][j] = ans;
}
// Returns length of the longest path with all characters consecutive
// to each other. This function first initializes dp array that
// is used to store results of subproblems, then it calls
// recursive DFS based function getLenUtil() to find max length path
int getLen(char mat[R][C], char s)
{
memset(dp, -1, sizeof dp);
int ans = 0;
for (int i=0; i<R; i++)
611
Chapter 86. Find length of the longest consecutive path from a given starting character
{
for (int j=0; j<C; j++)
{
// check for each possible starting point
if (mat[i][j] == s) {
// recur for all eight adjacent cells
for (int k=0; k<8; k++)
ans = max(ans, 1 + getLenUtil(mat,
i + x[k], j + y[k], s));
}
}
}
return ans;
}
// Driver program
int main() {
char mat[R][C] = { {'a','c','d'},
{ 'h','b','a'},
{ 'i','g','f'}};
cout << getLen(mat, 'a') << endl;
cout << getLen(mat, 'e') << endl;
cout << getLen(mat, 'b') << endl;
cout << getLen(mat, 'f') << endl;
return 0;
}
Java
class path
{
// tool matrices to recur for adjacent cells.
static int x[] = {0, 1, 1, -1, 1, 0, -1, -1};
static int y[] = {1, 0, 1, 1, -1, -1, 0, -1};
static int R = 3;
static int C = 3;
// dp[i][j] Stores length of longest consecutive path
// starting at arr[i][j].
static int dp[][] = new int[R][C];
// check whether mat[i][j] is a valid cell or not.
static boolean isvalid(int i, int j)
{
if (i < 0 || j < 0 || i >= R || j >= C)
return false;
612
Chapter 86. Find length of the longest consecutive path from a given starting character
return true;
}
// Check whether current character is adjacent to previous
// character (character processed in parent call) or not.
static boolean isadjacent(char prev, char curr)
{
return ((curr - prev) == 1);
}
// i, j are the indices of the current cell and prev is the
// character processed in the parent call.. also mat[i][j]
// is our current character.
static int getLenUtil(char mat[][], int i, int j, char prev)
{
// If this cell is not valid or current character is not
// adjacent to previous one (e.g. d is not adjacent to b )
// or if this cell is already included in the path than return 0.
if (!isvalid(i, j) || !isadjacent(prev, mat[i][j]))
return 0;
// If this subproblem is already solved , return the answer
if (dp[i][j] != -1)
return dp[i][j];
int ans = 0; // Initialize answer
// recur for paths with differnt adjacent cells and store
// the length of longest path.
for (int k=0; k<8; k++)
ans = Math.max(ans, 1 + getLenUtil(mat, i + x[k],
j + y[k], mat[i][j]));
// save the answer and return
return dp[i][j] = ans;
}
// Returns length of the longest path with all characters consecutive
// to each other. This function first initializes dp array that
// is used to store results of subproblems, then it calls
// recursive DFS based function getLenUtil() to find max length path
static int getLen(char mat[][], char s)
{
//assigning all dp values to -1
for(int i = 0;i<R;++i)
for(int j = 0;j<C;++j)
dp[i][j] = -1;
613
Chapter 86. Find length of the longest consecutive path from a given starting character
int ans = 0;
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
// check for each possible starting point
if (mat[i][j] == s) {
// recur for all eight adjacent cells
for (int k=0; k<8; k++)
ans = Math.max(ans, 1 + getLenUtil(mat,
i + x[k], j + y[k], s));
}
}
}
return ans;
}
public static void main(String args[])
{
char mat[][] = { {'a','c','d'},
{ 'h','b','a'},
{ 'i','g','f'}};
System.out.println(getLen(mat, 'a') );
System.out.println(getLen(mat, 'e') );
System.out.println(getLen(mat, 'b') );
System.out.println(getLen(mat, 'f') );
}
}/* This code is contributed by Rajat Mishra */
C#
614
Chapter 86. Find length of the longest consecutive path from a given starting character
615
Chapter 86. Find length of the longest consecutive path from a given starting character
// save the answer and return
return dp[i,j] = ans;
}
// Returns length of the longest path
// with all characters consecutive to
// each other. This function first
// initializes dp array that is used
// to store results of subproblems,
// then it calls recursive DFS based
// function getLenUtil() to find max
// length path
static int getLen(char [,]mat, char s)
{
//assigning all dp values to -1
for(int i = 0; i < R; ++i)
for(int j = 0; j < C; ++j)
dp[i,j] = -1;
int ans = 0;
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
// check for each possible
// starting point
if (mat[i,j] == s) {
// recur for all eight
// adjacent cells
for (int k = 0; k < 8; k++)
ans = Math.Max(ans, 1 +
getLenUtil(mat, i +
x[k], j + y[k], s));
}
}
}
return ans;
}
// Driver code`
public static void Main()
{
char [,]mat = { {'a','c','d'},
616
Chapter 86. Find length of the longest consecutive path from a given starting character
{ 'h','b','a'},
{ 'i','g','f'}};
Console.WriteLine(getLen(mat, 'a') );
Console.WriteLine(getLen(mat, 'e') );
Console.WriteLine(getLen(mat, 'b') );
Console.WriteLine(getLen(mat, 'f') );
}
}
// This code is contributed by nitin mittal.
Output:
4
0
3
4
Source
https://www.geeksforgeeks.org/find-length-of-the-longest-consecutive-path-in-a-character-matrix/
617
Chapter 87
Input : [1, 2, 3]
[1, 4, 9]
[76, 34, 21]
Output :
3
9
76
Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check
each element inside the row and find for the maximum element. Finally, print the element.
618
Chapter 87. Find maximum element of each row in a matrix
Output :
8
11
76
5
Source
https://www.geeksforgeeks.org/find-maximum-element-row-matrix/
619
Chapter 88
620
Chapter 88. Find maximum length Snake sequence
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use Dynamic Programming. For each cell of the matrix, we keep maximum
length of a snake which ends in current cell. The maximum length snake sequence will have
maximum value. The maximum value cell will correspond to tail of the snake. In order to
print the snake, we need to backtrack from tail all the way back to snake’s head.
Let T[i][i] represent maximum length of a snake which ends at cell (i, j), then for given
matrix M, the DP relation is defined as –
T[0][0] = 0
T[i][j] = max(T[i][j], T[i][j – 1] + 1) if M[i][j] = M[i][j – 1] ± 1
T[i][j] = max(T[i][j], T[i – 1][j] + 1) if M[i][j] = M[i – 1][j] ± 1
Below is C++ implementation of the idea –
CPP
621
Chapter 88. Find maximum length Snake sequence
list<Point> path;
Point pt = {i, j};
path.push_front(pt);
while (grid[i][j] != 0)
{
if (i > 0 &&
grid[i][j] - 1 == grid[i - 1][j])
{
pt = {i - 1, j};
path.push_front(pt);
i--;
}
else if (j > 0 &&
grid[i][j] - 1 == grid[i][j - 1])
{
pt = {i, j - 1};
path.push_front(pt);
j--;
}
}
return path;
}
// Function to find maximum length Snake sequence
void findSnakeSequence(int mat[M][N])
{
// table to store results of subproblems
int lookup[M][N];
// initialize by 0
memset(lookup, 0, sizeof lookup);
// stores maximum length of Snake sequence
int max_len = 0;
// store cordinates to snake's tail
int max_row = 0;
int max_col = 0;
// fill the table in bottom-up fashion
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
// do except for (0, 0) cell
622
Chapter 88. Find maximum length Snake sequence
if (i || j)
{
// look above
if (i > 0 &&
abs(mat[i - 1][j] - mat[i][j]) == 1)
{
lookup[i][j] = max(lookup[i][j],
lookup[i - 1][j] + 1);
if (max_len < lookup[i][j])
{
max_len = lookup[i][j];
max_row = i, max_col = j;
}
}
// look left
if (j > 0 &&
abs(mat[i][j - 1] - mat[i][j]) == 1)
{
lookup[i][j] = max(lookup[i][j],
lookup[i][j - 1] + 1);
if (max_len < lookup[i][j])
{
max_len = lookup[i][j];
max_row = i, max_col = j;
}
}
}
}
}
cout << "Maximum length of Snake sequence is: "
<< max_len << endl;
// find maximum length Snake sequence path
list<Point> path = findPath(lookup, mat, max_row,
max_col);
cout << "Snake sequence is:";
for (auto it = path.begin(); it != path.end(); it++)
cout << endl << mat[it->x][it->y] << " ("
<< it->x << ", " << it->y << ")" ;
}
// Driver code
int main()
{
623
Chapter 88. Find maximum length Snake sequence
int mat[M][N] =
{
{9, 6, 5, 2},
{8, 7, 6, 5},
{7, 3, 1, 6},
{1, 1, 1, 7},
};
findSnakeSequence(mat);
return 0;
}
Python3
624
Chapter 88. Find maximum length Snake sequence
625
Chapter 88. Find maximum length Snake sequence
[8, 7, 6, 5],
[7, 3, 1, 6],
[1, 1, 1, 7]]
findSnakeSequence(mat)
# This code is contributed
# by Soumen Ghosh
Output :
Time complexity of above solution is O(M*N). Auxiliary space used by above solution is
O(M*N). If we are not required to print the snake, space can be further reduced to O(N)
as we only uses the result from last row.
Reference: Stack Overflow
Source
https://www.geeksforgeeks.org/find-maximum-length-snake-sequence/
626
Chapter 89
Input : 1 3 5
2 6 9
3 6 9
Output : Median is 5
If we put all the values in a sorted
array A[] = 1 2 3 3 5 6 6 9 9)
Input: 1 3 4
2 5 6
7 8 9
Output: Median is 5
Simple Method: The simplest method to solve this problem is to store all the elements
of the given matrix in an array of size r*c. Then find the median element in this array.This
seems to be the simplest method but it would take extra memory.
Time Complexity = O(r*c)
Auxiliary Space = O(r*c)
An efficient approach for this problem is to use binary search algorithm. The idea is that
for a number to be median there should be exactly (n/2) numbers which are less than this
number. So, we try to find the count of numbers less than all the numbers. Below is the
step by step algorithm for this approach:
Algorithm:
627
Chapter 89. Find median in row wise sorted matrix
1. First we find the minimum and maximum elements in the matrix. Minimum element
can be easily found by comparing the first element of each row, and similarly the
maximum element can be found by comparing the last element of each row.
2. Then we use binary search on our range of numbers from minimum to maximum, we
find the mid of the min and max, and get count of numbers less than our mid. And
accordingly change the min or max.
3. For a number to be median, there should be (r*c)/2 numbers smaller than that num-
ber. So for every number, we get the count of numbers less than that by using
upper_bound() in each row of matrix, if it is less than the required count, the median
must be greater than the selected number, else the median must be less than or equal
to the selected number.
628
Chapter 89. Find median in row wise sorted matrix
min = mid + 1;
else
max = mid;
}
return min;
}
// driver program to check above functions
int main()
{
int r = 3, c = 3;
int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} };
cout << "Median is " << binaryMedian(m, r, c) << endl;
return 0;
}
Java
629
Chapter 89. Find median in row wise sorted matrix
// Find count of elements smaller than mid
for(int i = 0; i < r; ++i)
{
get = Arrays.binarySearch(m[i],mid);
// If element is not found in the array the
// binarySearch() method returns
// (-(insertion_point) - 1). So once we know
// the insertion point we can find elements
// Smaller than the searched element by the
// following calculation
if(get < 0)
get = Math.abs(get) - 1;
// If element is found in the array it returns
// the index(any index in case of duplicate). So we go to last
// index of element which will give the number of
// elements smaller than the number including
// the searched element.
else
{
while(get < m[i].length && m[i][get] == mid)
get += 1;
}
place = place + get;
}
if (place < desired)
min = mid + 1;
else
max = mid;
}
return min;
}
// Driver Program to test above method.
public static void main(String[] args)
{
int r = 3, c = 3;
int m[][]= { {1,3,5}, {2,6,9}, {3,6,9} };
System.out.println("Median is " + binaryMedian(m, r, c));
}
}
630
Chapter 89. Find median in row wise sorted matrix
Python
Output:
631
Chapter 89. Find median in row wise sorted matrix
Median is 5
Time Complexity: O(32 * r * log(c)). The upper bound function will take log(c) time
and is performed for each row. And since the numbers will be max of 32 bit, so binary
search of numbers from min to max will be performed in at most 32 ( log2(2^32) = 32 )
operations.
Auxiliary Space : O(1)
Source
https://www.geeksforgeeks.org/find-median-row-wise-sorted-matrix/
632
Chapter 90
Input : 0 1 0
1 1 1
0 1 1
Output : 4
Endless points are (1, 1), (1, 2),
(2, 1) and (2, 2). For all other
points path to some corner is
blocked at some point.
Input : 0 1 1
1 1 0
0 1 0
Output : 1
Endless point is (0, 2).
Naive Approach :
We traverse all positions, for every position, we check that does this position has endless
path or not. If yes then count it otherwise ignore it. But as usual its time complexity seems
to be high.
Time complexity : O(n3 )
633
Chapter 90. Find number of endless points
Also, we can say that any position (i,j) will have an endless row if (i,j+1) will have an endless
row and value of (i,j) is 1.
Similarly, we can say that any position (i,j) will have an endless column if (i+1,j) will have
an endless column and value of (i,j) is 1.
So we should maintain two matrices one for row and one for column. Always start from
right most position for row and bottom most position for column and only check for next
position whether it has endless path or not.
And Finally, if any position will have an endless path in both row and column matrix then
that position is said to have an endless path.
C++
634
Chapter 90. Find number of endless points
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100;
// Returns count of endless points
int countEndless(bool input[][MAX], int n)
{
bool row[n][n], col[n][n];
// Fills column matrix. For every column, start
// from every last row and fill every entry as
// blockage after a 0 is found.
for (int j=0; j<n; j++)
{
// flag which will be zero once we get a '0'
// and it will be 1 otherwise
bool isEndless = 1;
for (int i=n-1; i>=0; i--)
{
// encountered a '0', set the isEndless
// variable to false
if (input[i][j] == 0)
isEndless = 0;
col[i][j] = isEndless;
}
}
// Similarly, fill row matrix
for (int i=0; i<n; i++)
{
bool isEndless = 1;
for (int j= n-1; j>=0; j--)
{
if (input[i][j] == 0)
isEndless = 0;
row[i][j] = isEndless;
}
}
// Calculate total count of endless points
int ans = 0;
for (int i=0; i<n; i++)
for (int j=1; j<n; j++)
// If there is NO blockage in row
// or column after this point,
// increment result.
635
Chapter 90. Find number of endless points
Java
636
Chapter 90. Find number of endless points
isEndless = false;
col[i][j] = isEndless;
}
}
// Similarly, fill row matrix
for (int i = 0; i < n; i++)
{
boolean isEndless = true;
for (int j = n-1; j >= 0; j--)
{
if (input[i][j] == false)
isEndless = false;
row[i][j] = isEndless;
}
}
// Calculate total count of endless points
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 1; j < n; j++)
// If there is NO blockage in row
// or column after this point,
// increment result.
if (row[i][j] && col[i][j])
ans++;
return ans;
}
//driver code
public static void main(String arg[])
{
boolean input[][] = {
{true, false, true, true},
{false, true, true, true},
{true, true, true, true},
{false, true, true, false}};
int n = 4;
System.out.print(countEndless(input, n));
}
}
// This code is contributed by Anant Agarwal.
637
Chapter 90. Find number of endless points
C#
638
Chapter 90. Find number of endless points
}
}
// Calculate total count of
// endless points
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 1; j < n; j++)
// If there is NO blockage
// in row or column after
// this point, increment
// result.
if (row[i,j] && col[i,j])
ans++;
return ans;
}
//Driver code
public static void Main()
{
bool [,]input = {
{true, false, true, true},
{false, true, true, true},
{true, true, true, true},
{false, true, true, false}};
int n = 4;
Console.Write(countEndless(input, n));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to find
// count of endless points
// Returns count of
// endless points
function countEndless($input, $n)
{
// Fills column matrix. For
// every column, start from
639
Chapter 90. Find number of endless points
640
Chapter 90. Find number of endless points
// Driver code
$input = array(array(1, 0, 1, 1),
array(0, 1, 1, 1),
array(1, 1, 1, 1),
array(0, 1, 1, 0));
$n = 4;
echo countEndless($input, $n);
// This code is contributed
// by shiv_bhakt.
?>
Output:
Source
https://www.geeksforgeeks.org/find-number-endless-points/
641
Chapter 91
Input :
A[2][2]: 1 1
1 1
B[2][2]: 1 2
3 4
Output : 3
Explaination :
1 1 -> 1 2 -> 1 2 -> 1 2
1 1 -> 1 2 -> 2 3 -> 3 4
Input :
A[2][2]: 1 1
1 0
B[2][2]: 1 2
3 4
Output : -1
Explaination : No transformation will make A and B equal.
642
Chapter 91. Find number of transformation to make two Matrix Equal
-> Incrementing any row of A[][] is same as decrementing the same row of B[][]. So, we can
have the solution after having the transformation on only one matrix either incrementing
or decrementing.
-> For every transformation either 1st row/ 1st column element necessarily got changed,
same is true for other i-th row/column.
-> If ( A[i][j] – A[i][0] – A[0][j] + A[0][0] != 0) then no solution exists.
-> Elements of 1st row and 1st column only leads to result.
// If transformation is possible
// calculate total transformation
result = 0;
for (i = 0; i < n; i++)
result += abs(A[i][0])
for (j = 0; j < m; j++)
result += abs(A[0][j] - A[0][0]);
return abs(result);
C++
643
Chapter 91. Find number of transformation to make two Matrix Equal
644
Chapter 91. Find number of transformation to make two Matrix Equal
Java
645
Chapter 91. Find number of transformation to make two Matrix Equal
{1, 1, 1},
{1, 1, 1} };
int B[][] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
System.out.println(countOps(A, B, 3, 3)) ;
}
}
// This code is contributed by KRV.
C#
646
Chapter 91. Find number of transformation to make two Matrix Equal
PHP
<?php
// PHP program to find
// number of countOpsation
// to make two matrix equals
function countOps($A, $B,
$m, $n)
{
$MAX = 1000;
// Update matrix A[][]
// so that only A[][]
// has to be countOpsed
for ($i = 0; $i < $n; $i++)
for ($j = 0; $j < $m; $j++)
$A[$i][$j] -= $B[$i][$j];
// Check necessary condition
// for condition for
// existence of full countOpsation
647
Chapter 91. Find number of transformation to make two Matrix Equal
Output:
12
Source
https://www.geeksforgeeks.org/find-number-transformation-make-two-matrix-equal/
648
Chapter 92
Input:
mat[N][N] = { {'a', 'b', 'c', 'd', 'e'},
{'f', 'g', 'h', 'i', 'j'},
{'k', 'l', 'm', 'n', 'o'},
{'p', 'q', 'r', 's', 't'},
{'u', 'v', 'w', 'x', 'y'}};
pattern = "pqrs";
Output: Horizontal
We strongly recommend you to minimize your browser and try this yourself
first.
A simple solution is for each row and column, use Naive pattern searching algorithm to find
the orientation of pattern in the matrix. The time complexity of Naive pattern searching
algorithm for every row is O(NM) where N is size of the matrix and M is length of the
pattern. So, the time complexity of this solution will be O(N*(NM)) as each of N rows
and N columns takes O(NM) time.
Can we do better?
The idea is to use KMP pattern matching algorithm for each row and column. The KMP
matching algorithm improves the worst case to O(N + M). The total cost of a KMP search
is linear in the number of characters of string and pattern. For a N x N matrix and pattern
of length M, complexity of this solution will be O(N*(N+M)) as each of N rows and N
columns will take O(N + M) time.
649
Chapter 92. Find orientation of a pattern in a matrix
650
Chapter 92. Find orientation of a pattern in a matrix
651
Chapter 92. Find orientation of a pattern in a matrix
return;
}
// Construct an array to store i'th column
for (int j = 0; j < N; j++)
col[j] = *(mat[j] + i);
// Search in column i
if (KMPSearch(pat, col))
printf("Vertical\n");
}
// to avoid memory leak
free(col);
}
// Driver program to test above function
int main()
{
char mat[N][N] =
{
{'a', 'b', 'c', 'd', 'e'},
{'f', 'g', 'h', 'i', 'j'},
{'k', 'l', 'm', 'n', 'o'},
{'p', 'q', 'r', 's', 't'},
{'u', 'v', 'w', 'x', 'y'}
};
char pat[] = "pqrs";
findOrientation(mat, pat);
return 0;
}
Output :
Horizontal
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-orientation-of-a-pattern-in-a-matrix/
652
Chapter 93
Find pair of rows in a binary matrix that has maximum bit difference - GeeksforGeeks
Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has
maximum bit difference
Examples:
653
Chapter 93. Find pair of rows in a binary matrix that has maximum bit difference
{1, 0 ,0 ,0 }}
Output : (1, 3) or (2 ,4 ) or (3 ,4 )
They all are having maximum bit difference
that is 3
Simple solution of this problem is that pick each row of binary matrix one -by -one and
compute maximum bit difference with rest of the rows of matrix .at last return rows those
have maximum bit difference .
An Efficient solution using Trie Data Structure. Below is algorithm.
654
Chapter 93. Find pair of rows in a binary matrix that has maximum bit difference
// utility function insert new row in trie
void insert(TrieNode *root, int Mat[][MAX], int n,
int row_index)
{
TrieNode * temp = root;
for (int i=0; i<n; i++)
{
// Add a new Node into trie
if(temp->Child[ Mat[row_index][i] ] == NULL)
temp->Child[ Mat[row_index][i] ] = getNode();
// move current node to point next node in trie
temp = temp->Child[ Mat[row_index][i] ];
}
// store index of currently inserted row
temp->leaf = row_index +1 ;
}
// utility function calculate maximum bit difference of
// current row with previous visited row of binary matrix
pair<int, int> maxBitDiffCount(TrieNode * root,
int Mat[][MAX], int n, int row_index)
{
TrieNode * temp = root;
int count = 0;
// Find previous visited row of binary matrix
// that has starting bit same as current row
for (int i= 0 ; i < n ; i++)
{
// First look for same bit in trie
if (temp->Child[ Mat[row_index][i] ] != NULL)
temp = temp->Child[ Mat[row_index][i] ];
// Else looking for opposite bit
else if (temp->Child[1 - Mat[row_index][i]] != NULL)
{
temp = temp->Child[1- Mat[row_index][i]];
count++;
}
}
int leaf_index = temp->leaf;
int count1 = 0 ;
temp = root;
655
Chapter 93. Find pair of rows in a binary matrix that has maximum bit difference
// Find previous visited row of binary matrix
// that has starting bit opposite to current row
for (int i= 0 ; i < n ; i++)
{
// First looking for opposite bit
if (temp->Child[ 1 - Mat[row_index][i] ] !=NULL)
{
temp = temp->Child[ 1- Mat[row_index][i] ];
count1++;
}
// Else look for same bit in trie
else if (temp->Child[ Mat[row_index][i] ] != NULL)
temp = temp->Child[ Mat[row_index][i] ];
}
pair <int ,int> P = count1 > count ?
make_pair(count1, temp->leaf):
make_pair(count, leaf_index);
// return pair that contain both bit difference
// count and index of row with we get bit
// difference
return P;
}
// Returns maximum bit difference pair of row
void maxDiff( int mat[][MAX], int n, int m)
{
TrieNode * root = getNode();
// Insert first matrix row in trie
insert(root, mat, m, 0);
int max_bit_diff = INT_MIN;
pair <int ,int> P, temp ;
// Traverse all rest row of binary matrix
for (int i = 1 ; i < n; i++)
{
// compute bit difference with previous visited
// rows of matrix
temp = maxBitDiffCount(root, mat, m ,i);
// update maximum bit difference
if (max_bit_diff < temp.first )
{
656
Chapter 93. Find pair of rows in a binary matrix that has maximum bit difference
max_bit_diff = temp.first;
P = make_pair( temp.second, i+1);
}
// insert current row value into Trie
insert(root, mat, m, i );
}
// print maximum bit difference pair in row
cout << "(" << P.first <<", "<< P.second << ")";
}
// Driver program
int main()
{
int mat[][MAX] = {{0 ,1 ,0 ,1, 0 },
{1, 0, 1 ,1 ,0 },
{0 ,0 ,1 ,0, 1 }
};
maxDiff(mat, 3, 5) ;
return 0;
}
Output:
1 , 3
Source
https://www.geeksforgeeks.org/find-pair-rows-binary-matrix-maximum-bit-difference/
657
Chapter 94
Find pairs with given sum such that elements of pair are in different rows - GeeksforGeeks
Given a matrix of distinct values and a sum. The task is to find all the pairs in given whose
summation is equal to given sum. Each element of pair must be from different rows i.e; pair
must not lie in same row.
Examples:
Method 1 (Simple)
A simple solution for this problem is to one by one take each element of all rows and find
pair starting from immediate next row with in matrix. Time complexity for this approach
will be O(n4 ).
• Sort all the rows in ascending order. Time complexity for this preprocessing will be
O(n2 logn).
658
Chapter 94. Find pairs with given sum such that elements of pair are in different rows
• Now we will select each row one by one and find pair element in remaining rows after
current row.
• Take two iterators left and right. left iterator points left corner of current i’th row
and right iterator points right corner of next j’th row in which we are going to find
pair element.
• If mat[i][left] + mat[j][right] < sum then left++ i.e; move in i’th row towards
right corner, otherwise right++ i.e; move in j’th row towards left corner.
CPP
659
Chapter 94. Find pairs with given sum such that elements of pair are in different rows
right--;
}
}
}
}
}
// Driver program to run the case
int main()
{
int n = 4, sum = 11;
int mat[][MAX] = {{1, 3, 2, 4},
{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}};
pairSum(mat, n, sum);
return 0;
}
Java
660
Chapter 94. Find pairs with given sum such that elements of pair are in different rows
right--;
}
else {
if ((mat[i][left] + mat[j][right]) < sum)
left++;
else
right--;
}
}
}
}
}
// Driver code
public static void main(String[] args) {
int n = 4, sum = 11;
int mat[]
[] = {{1 , 3, 2, 4},
{5 , 8, 7, 6},
{9 , 10, 13, 11},
{12, 0, 14, 15}};
pairSum(mat, n, sum);
}
}
// This code is contributed by Anant Agarwal.
Output:
Method 3 (Hashing)
1. Create an empty hash table and store all elements of matrix in hash as key and their
locations as values.
2. Traverse the matrix again to check for every element whether its pair exists in hash
table or not. If exists, then compare row numbers. If row numbers are not same, then
print the pair.
CPP
661
Chapter 94. Find pairs with given sum such that elements of pair are in different rows
662
Chapter 94. Find pairs with given sum such that elements of pair are in different rows
}
// Driver program
int main()
{
int n = 4, sum = 11;
int mat[][MAX]= {{1, 3, 2, 4},
{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}};
pairSum(mat, n, sum);
return 0;
}
Output :
(1, 10), (3, 8), (2, 9), (4, 7), (11, 0),
One important thing is, when we traverse a matrix, a pair may be printed twice. To make
sure that a pair is printed only once, we check if row number of other element picked from
hash table is more than row number of current element.
Time Complexity : O(n2 ) under the assumption that hash table insert and search operations
take O(1) time.
Source
https://www.geeksforgeeks.org/find-pairs-given-sum-elements-pair-different-rows/
663
Chapter 95
| 1 | | 1 1 |
Examples:
Input : mat[][] =
{
1, 0,
1, 1,
}
Output : 8
Cell (1,0) and (1,1) making a L shape whose perimeter is 8.
Input : mat[][] =
{
0, 1, 0, 0, 0,
1, 1, 1, 0, 0,
1, 0, 0, 0, 0
}
Output : 12
664
Chapter 95. Find perimeter of shapes formed with 1s in binary matrix
The idea is to traverse the matrix, find all ones and find their contribution in perimeter.
The maximum contribution of a 1 is four if it is surrounded by all 0s. The contribution
reduces by one with 1 around it.
Algorithm for solving this problem:
1. Traverse the whole matrix and find the cell having value equal to 1.
2. Calculate the number of closed side for that cell and add, 4 – number of closed side
to the total perimeter.
665
Chapter 95. Find perimeter of shapes formed with 1s in binary matrix
int perimeter = 0;
// Traversing the matrix and finding ones to
// calculate their contribution.
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (mat[i][j])
perimeter += (4 - numofneighbour(mat, i ,j));
return perimeter;
}
// Driven Program
int main()
{
int mat[R][C] =
{
0, 1, 0, 0, 0,
1, 1, 1, 0, 0,
1, 0, 0, 0, 0,
};
cout << findperimeter(mat) << endl;
return 0;
}
Java
666
Chapter 95. Find perimeter of shapes formed with 1s in binary matrix
// LEFT
if (j > 0 && mat[i][j - 1] == 1)
count++;
// DOWN
if (i < R - 1 && mat[i + 1][j] == 1)
count++;
// RIGHT
if (j < C - 1 && mat[i][j + 1] == 1)
count++;
return count;
}
// Returns sum of perimeter of shapes
// formed with 1s
static int findperimeter(int mat[][])
{
int perimeter = 0;
// Traversing the matrix and
// finding ones to calculate
// their contribution.
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (mat[i][j] == 1)
perimeter += (4 -
numofneighbour(mat, i, j));
return perimeter;
}
// Driver code
public static void main(String[] args)
{
int mat[][] = {{0, 1, 0, 0, 0},
{1, 1, 1, 0, 0},
{1, 0, 0, 0, 0}};
System.out.println(findperimeter(mat));
}
}
// This code is contributed by Anant Agarwal.
667
Chapter 95. Find perimeter of shapes formed with 1s in binary matrix
Output:
12
Source
https://www.geeksforgeeks.org/find-perimeter-shapes-formed-1s-binary-matrix/
668
Chapter 96
Basic Approach : Traverse whole of matrix and for each row find the number of 1 and
among all that keep updating the row number with maximum number of 1. This approach
will result in O(n^2) time complexity.
Better Approach : We can perform a better if we try to apply binary search for finding
position of first 1 in each row and as per that we can find the number of 1 from each row
as each row is in sorted order. This will result in O(nlogn) time complexity.
669
Chapter 96. Find row number of a binary matrix having maximum number of 1s
Efficient Approach : Start with top left corner with index (1, n) and try to go left until
you reach last 1 in that row (jth column), now if we traverse left to that row, we will find 0,
so switch to the row just below, with same column. Now your position will be (2, j) again
in 2nd row if jth element if 1 try to go left until you find last 1 otherwise in 2nd row if
jth element is 0 go to next row. So Finally say if you are at any ith row and jth column
which is index of last 1 from right in that row, increment i. So now if we have Aij = 0 again
increment i otherwise keep decreasing j until you find last 1 in that particular row.
Sample Illustration :
Algorithm :
C++
670
Chapter 96. Find row number of a binary matrix having maximum number of 1s
Java
671
Chapter 96. Find row number of a binary matrix having maximum number of 1s
// find left most position of 1 in
// a row find 1st zero in a row
while (arr[i][j] == 1 && j >= 0) {
row = i;
j--;
}
}
System.out.print("Row number = "
+ (row + 1));
System.out.print(", MaxCount = "
+ (N - 1 - j));
}
// Driver code
public static void main(String[] args) {
int arr[][] = {{0, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 0},
{0, 1, 1, 1}};
findMax(arr);
}
}
// This code is contributed by Anant Agarwal.
Python3
672
Chapter 96. Find row number of a binary matrix having maximum number of 1s
j -= 1
print("Row number = " , row + 1,
", MaxCount = ", N - 1 - j)
# driver program
arr = [ [0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 1, 1, 1] ]
findMax(arr)
# This code is contributed by Sam007
C#
673
Chapter 96. Find row number of a binary matrix having maximum number of 1s
PHP
<?php
// PHP program to find
// row with maximum 1
// in row sorted
// binary matrix
$N = 4;
// function for finding
// row with maximum 1
function findMax ($arr)
{
global $N;
$row = 0; $i;
$j=$N - 1;
for ($i = 0; $i < $N; $i++)
{
// find left most position
// of 1 in a row find 1st
// zero in a row
while ($arr[$i][$j] == 1 &&
$j >= 0)
{
$row = $i;
$j--;
}
}
echo "Row number = " , $row + 1;
echo ", MaxCount = " , $N - 1 - $j;
}
// Driver Code
$arr = array(array(0, 0, 0, 1),
array(0, 0, 0, 1),
674
Chapter 96. Find row number of a binary matrix having maximum number of 1s
array(0, 0, 0, 0),
array(0, 1, 1, 1));
findMax($arr);
// This code is contributed by vt_m.
?>
Output:
Source
https://www.geeksforgeeks.org/find-row-number-binary-matrix-maximum-number-1s/
675
Chapter 97
Input:
A 12 x 10 matrix with landmines marked as 0
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 0 1 1 1 1 1 1 1 1 ]
[ 1 1 1 0 1 1 1 1 1 1 ]
[ 1 1 1 1 0 1 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 1 1 0 1 1 1 1 ]
[ 1 0 1 1 1 1 1 1 0 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 0 1 1 1 1 0 1 1 1 1 ]
[ 1 1 1 1 1 1 1 1 1 1 ]
[ 1 1 1 0 1 1 1 1 1 1 ]
Output:
Length of shortest safe route is 13 (Highlighted in Bold)
676
Chapter 97. Find shortest safe route in a path with landmines
The idea is to use Backtracking. We first mark all adjacent cells of the landmines as unsafe.
Then for each safe cell of first column of the matrix, we move forward in all allowed directions
and recursively checks if they leads to the destination or not. If destination is found, we
update the value of shortest path else if none of the above solutions work we return false
from our function.
Below is C++ implementation of above idea –
677
Chapter 97. Find shortest safe route in a path with landmines
{
// if a landmines is found
if (mat[i][j] == 0)
{
// mark all adjacent cells
for (int k = 0; k < 4; k++)
if (isValid(i + rowNum[k], j + colNum[k]))
mat[i + rowNum[k]][j + colNum[k]] = -1;
}
}
}
// mark all found adjacent cells as unsafe
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
{
if (mat[i][j] == -1)
mat[i][j] = 0;
}
}
// Uncomment below lines to print the path
/*for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
{
cout << std::setw(3) << mat[i][j];
}
cout << endl;
}*/
}
// Function to find shortest safe Route in the
// matrix with landmines
// mat[][] - binary input matrix with safe cells marked as 1
// visited[][] - store info about cells already visited in
// current route
// (i, j) are cordinates of the current cell
// min_dist --> stores minimum cost of shortest path so far
// dist --> stores current path cost
void findShortestPathUtil(int mat[R][C], int visited[R][C],
int i, int j, int &min_dist, int dist)
{
// if destination is reached
if (j == C-1)
{
// update shortest path found so far
678
Chapter 97. Find shortest safe route in a path with landmines
679
Chapter 97. Find shortest safe route in a path with landmines
680
Chapter 97. Find shortest safe route in a path with landmines
Output:
Source
https://www.geeksforgeeks.org/find-shortest-safe-route-in-a-path-with-landmines/
681
Chapter 98
Find size of the largest ’+’ formed by all ones in a binary matrix - GeeksforGeeks
Given a N X N binary matrix, find the size of the largest ‘+’ formed by all 1s.
Example:
682
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
For above matrix, largest ‘+’ would be formed by highlighted part of size 17.
The idea is to maintain four auxiliary matrices left[][], right[][], top[][], bottom[][] to store
consecutive 1’s in every direction. For each cell (i, j) in the input matrix, we store below
information in these four matrices –
683
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
After computing value for each cell of above matrices, the largest + would be formed by a
cell of input matrix that has maximum value by considering minimum of (left(i, j), right(i,
j), top(i, j), bottom(i, j) )
We can use Dynamic Programming to compute the total amount of consecutive 1’s in every
direction.
if mat(i, j) == 1
left(i, j) = left(i, j - 1) + 1
else left(i, j) = 0
if mat(i, j) == 1
top(i, j) = top(i - 1, j) + 1;
else
top(i, j) = 0;
if mat(i, j) == 1
bottom(i, j) = bottom(i + 1, j) + 1;
else
bottom(i, j) = 0;
if mat(i, j) == 1
right(i, j) = right(i, j + 1) + 1;
else
right(i, j) = 0;
684
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
685
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
686
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
{ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 },
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 0, 1, 1 },
{ 1, 1, 0, 0, 1, 0, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }
};
cout << findLargestPlus(mat);
return 0;
}
Java
687
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
688
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
689
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
}
// This code is contributed by vt_m.
C#
690
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
691
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
bottom[i,j]),Math.Min(left[i,j],
right[i,j]));
// largest + would be formed by a
// cell that has maximum value
if (len > n)
n = len;
}
}
// 4 directions of length n - 1 and 1 for
// middle cell
if (n > 0)
return 4 * (n - 1) + 1;
// matrix contains all 0's
return 0;
}
/* Driver function to test above functions */
public static void Main()
{
// Binary Matrix of size N
int [,]mat = {
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 },
{ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 0, 1, 1 },
{ 1, 1, 0, 0, 1, 0, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }
};
Console.Write(findLargestPlus(mat));
}
}
// This code is contributed by KRV.
Output:
17
692
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix
Source
https://www.geeksforgeeks.org/find-size-of-the-largest-formed-by-all-ones-in-a-binary-matrix/
693
Chapter 99
Find sum of all elements in a matrix except the elements in row and/or column of given
cell? - GeeksforGeeks
Given a 2D matrix and a set of cell indexes e.g., an array of (i, j) where i indicates row
and j column. For every given cell index (i, j), find sums of all matrix elements except the
elements present in i’th row and/or j’th column.
Example:
mat[][] = { {1, 1, 2}
{3, 4, 6}
{5, 3, 2} }
Array of Cell Indexes: {(0, 0), (1, 1), (0, 1)}
Output: 15, 10, 16
We strongly recommend you to minimize your browser and try this yourself
first.
A Naive Solution is to one by once consider all given cell indexes. For every cell index (i,
j), find the sum of matrix elements that are not present either at i’th row or at j’th column.
Below is C++ implementation of the Naive approach.
#include<bits/stdc++.h>
#define R 3
#define C 3
694
Chapter 99. Find sum of all elements in a matrix except the elements in row and/or
column of given cell?
Output:
15
10
16
Time complexity of the above solution is O(n * R * C) where n is number of given cell
indexes and R x C is matrix size.
An Efficient Solution can compute all sums in O(R x C + n) time. The idea is to
precompute total sum, row and column sums before processing the given array of indexes.
Below are details
695
Chapter 99. Find sum of all elements in a matrix except the elements in row and/or
column of given cell?
// An efficient C++ program to compute sum for given array of cell indexes
#include<bits/stdc++.h>
#define R 3
#define C 3
using namespace std;
// A structure to represent a cell index
struct Cell
{
int r; // r is row, varies from 0 to R-1
int c; // c is column, varies from 0 to C-1
};
void printSums(int mat[][C], struct Cell arr[], int n)
{
int sum = 0;
int row[R] = {};
int col[C] = {};
// Compute sum of all elements, sum of every row and sum every column
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
sum += mat[i][j];
col[j] += mat[i][j];
row[i] += mat[i][j];
}
}
// Compute the desired sum for all given cell indexes
for (int i=0; i<n; i++)
{
int ro = arr[i].r, co = arr[i].c;
cout << sum - row[ro] - col[co] + mat[ro][co] << endl;
}
}
// Driver program to test above function
int main()
{
int mat[][C] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}};
struct Cell arr[] = {{0, 0}, {1, 1}, {0, 1}};
696
Chapter 99. Find sum of all elements in a matrix except the elements in row and/or
column of given cell?
int n = sizeof(arr)/sizeof(arr[0]);
printSums(mat, arr, n);
return 0;
}
Output:
15
10
16
Source
https://www.geeksforgeeks.org/find-sum-of-all-elements-in-a-matrix-except-the-elements-in-given-row-andor-colum
697
Chapter 100
Given a N*M matrix A[][] representing a 3D figure. The height of the building at
Explanation :
The total surface area is 6 i.e 6 side of
the figure and each are of height 1.
Approach : To find the surface area we need to consider the contribution of all the six
sides of the given 3D figure. We will solve the questions in part to make it easy. The base of
the Figure will always contribute N*M to the total surface area of the figure, and same N*M
area will be contributed by the top of the figure. Now, to calculate the area contributed by
the walls, we will take out the absolute difference between the height of two adjacent wall.
The difference will be the contribution in the total surface area.
Below is the implementation of the above idea :
698
Chapter 100. Find the Surface area of a 3D figure
C++
699
Chapter 100. Find the Surface area of a 3D figure
/* If its the rightmost block of the matrix
it will contribute area equal to its height
as a wall on the right of the figure */
if (i == N - 1)
ans += A[i][j];
/* If its the lowest block of the matrix it will
contribute area equal to its height as a wall
on the bottom of the figure */
if (j == M - 1)
ans += A[i][j];
}
}
// Adding the contribution by the base and top of the figure
ans += N * M * 2;
return ans;
}
// Driver program
int main()
{
int A[N][M] = { { 1, 3, 4 },
{ 2, 2, 3 },
{ 1, 2, 4 } };
cout << surfaceArea(A) << endl;
return 0;
}
Java
700
Chapter 100. Find the Surface area of a 3D figure
701
Chapter 100. Find the Surface area of a 3D figure
}
// Adding the contribution by
// the base and top of the figure
ans += N * M * 2;
return ans;
}
// Driver code
public static void main (String[] args)
{
int A[][] = {{ 1, 3, 4 },
{ 2, 2, 3 },
{ 1, 2, 4 } };
System.out.println(surfaceArea(A));
}
}
// This code is contributed By Anant Agarwal.
C#
702
Chapter 100. Find the Surface area of a 3D figure
703
Chapter 100. Find the Surface area of a 3D figure
// Driver code
public static void Main ()
{
int [,]A = {{ 1, 3, 4 },
{ 2, 2, 3 },
{ 1, 2, 4 } };
Console.WriteLine(surfaceArea(A));
}
}
// This code is contributed By vt_m.
PHP
<?php
// PHP program to find the
// Surface area of a 3D figure
// Declaring the size
// of the matrix
$M = 3;
$N = 3;
// Absolute Difference
// between the height of
// two consecutive blocks
function contribution_height($current,
$previous)
{
return abs($current - $previous);
}
// Function To calculate
// the Total surfaceArea.
function surfaceArea($A)
{
global $M;
global $N;
$ans = 0;
// Traversing the matrix.
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $M; $j++)
{
704
Chapter 100. Find the Surface area of a 3D figure
705
Chapter 100. Find the Surface area of a 3D figure
$ans += $N * $M * 2;
return $ans;
}
// Driver Code
$A = array(array(1, 3, 4),
array(2, 2, 3),
array(1, 2, 4));
echo surfaceArea($A);
// This code is contributed By mits
?>
Output :
60
Source
https://www.geeksforgeeks.org/find-surface-area-3d-figure/
706
Chapter 101
Find the largest area rectangular sub-matrix whose sum is equal to k - GeeksforGeeks
Given a 2D matrix mat[][] and a value k. Find the largest rectangular sub-matrix whose
sum is equal to k.
Example:
Naive Approach: Check every possible rectangle in given 2D array having sum equal to
‘k’ and print the largest one. This solution requires 4 nested loops and time complexity of
this solution would be O(n^4).
Efficient Approach: Longest sub-array having sum k for 1-D array can be used to reduce
the time complexity to O(n^3). The idea is to fix the left and right columns one by one
and find the longest sub-array having sum equal to ‘k’ for contiguous rows for every left and
right column pair. We basically find top and bottom row numbers (which are part of the
707
Chapter 101. Find the largest area rectangular sub-matrix whose sum is equal to k
largest sub-matrix) for every fixed left and right column pair. To find the top and bottom
row numbers, calculate sum of elements in every row from left to right and store these sums
in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i.
Now, apply Longest sub-array having sum k 1D algorithm on temp[], and get the longest
sub-array having sum equal to ‘k’ of temp[]. This length would be the maximum possible
length with left and right as boundary columns. Set the ‘top’ and ‘bottom’ row indexes for
the left right column pair and calculate the area. In similar manner get the top, bottom,
left, right indexes for other sub-matrices having sum equal to ‘k’ and print the one having
maximum area.
708
Chapter 101. Find the largest area rectangular sub-matrix whose sum is equal to k
// check if 'sum-k' is present in 'um'
// or not
if (um.find(sum - k) != um.end()) {
// update maxLength and start and end points
if (maxLen < (i - um[sum - k])) {
maxLen = i - um[sum - k];
start = um[sum - k] + 1;
end = i;
}
}
}
// Return true if maximum length is non-zero
return (maxLen != 0);
}
// function to find the largest area rectangular
// sub-matrix whose sum is equal to k
void sumZeroMatrix(int mat[][MAX], int row, int col, int k)
{
// Variables to store the temporary values
int temp[row], area;
bool sum;
int up, down;
// Variables to store the final output
int fup = 0, fdown = 0, fleft = 0, fright = 0;
int maxArea = INT_MIN;
// Set the left column
for (int left = 0; left < col; left++) {
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column
// set by outer loop
for (int right = left; right < col; right++) {
// Calculate sum between current left
// and right column for every row 'i'
for (int i = 0; i < row; i++)
temp[i] += mat[i][right];
// Find largest subarray with 'k' sum in
// temp[]. The sumEqualToK() function also
// sets values of 'up' and 'down;'. So
// if 'sum' is true then rectangle exists between
709
Chapter 101. Find the largest area rectangular sub-matrix whose sum is equal to k
710
Chapter 101. Find the largest area rectangular sub-matrix whose sum is equal to k
int main()
{
int mat[][MAX] = { { 1, 7, -6, 5 },
{ -8, 6, 7, -2 },
{ 10, -15, 3, 2 },
{ -5, 2, 0, 9 } };
int row = 4, col = 4;
int k = 7;
sumZeroMatrix(mat, row, col, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-the-largest-area-rectangular-sub-matrix-whose-sum-is-equal-to-k/
711
Chapter 102
Find the largest rectangle of 1’s with swapping of columns allowed - GeeksforGeeks
Given a matrix with 0 and 1’s, find the largest rectangle of all 1’s in the matrix. The
rectangle can be formed by swapping any pair of columns of given matrix.
Example:
712
Chapter 102. Find the largest rectangle of 1’s with swapping of columns allowed
The idea is to use an auxiliary matrix to store count of consecutive 1’s in every column.
Once we have these counts, we sort all rows of auxiliary matrix in non-increasing order of
counts. Finally traverse the sorted rows to find the maximum area.
Note : After forming the auxiliary matrix each row becomes independent, hence we can swap
or sort each row independently.It is because we can only swap columns, so we have made
each row independent and find the max area of rectangle possible with row and column.
Below are detailed steps for first example mentioned above.
Step 1: First of all, calculate no. of consecutive 1’s in every column. An auxiliary array
hist[][] is used to store the counts of consecutive 1’s. So for the above first example, contents
of hist[R][C] would be
0 1 0 1 0
0 2 0 2 1
1 3 0 3 0
1 1 0 0 0
2 2 1 0 0
3 3 1 0 0
This step can be done in O(R * (R + C)). Since we know that the values are in range from
0 to R, we can use counting sort for every row.
The sorting is actually the swapping of columns. If we look at the 3rd row under step 2:
33100
The sorted row corresponds to swapping the columns so that the column with the highest
possible rectangle is placed first, after that comes the column that allows the second highest
rectangle and so on. So, in the example there are 2 columns that can form a rectangle of
height 3. That makes an area of 3*2=6. If we try to make the rectangle wider the height
drops to 1, because there are no columns left that allow a higher rectangle on the 3rd row.
Step 3: Traverse each row of hist[][] and check for the max area. Since every row is sorted
by count of 1’s, current area can be calculated by multiplying column number with value in
hist[i][j]. This step also takes O(R * C) time.
Below is C++ implementation based of above idea.
713
Chapter 102. Find the largest rectangle of 1’s with swapping of columns allowed
714
Chapter 102. Find the largest rectangle of 1’s with swapping of columns allowed
Output:
Time complexity of above solution is O(R * (R + C)) where R is number of rows and C
is number of columns in input matrix. Extra space: O(R * C)
This article is contributed by Shivprasad Choudhary. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Improved By : chirag dawra, Mahip Jain
Source
https://www.geeksforgeeks.org/find-the-largest-rectangle-of-1s-with-swapping-of-columns-allowed/
715
Chapter 103
The idea is simple, we calculate longest path beginning with every cell. Once we have
computed longest for all cells, we return maximum of all longest paths. One important
observation in this approach is many overlapping subproblems. Therefore this problem can
be optimally solved using Dynamic Programming.
Below is Dynamic Programming based implementation that uses a lookup table dp[][] to
check if a problem is already solved or not.
C/C++
#include<bits/stdc++.h>
#define n 3
using namespace std;
716
Chapter 103. Find the longest path in a matrix with given constraints
// Returns length of the longest path beginning with mat[i][j].
// This function mainly uses lookup table dp[n][n]
int findLongestFromACell(int i, int j, int mat[n][n], int dp[n][n])
{
// Base case
if (i<0 || i>=n || j<0 || j>=n)
return 0;
// If this subproblem is already solved
if (dp[i][j] != -1)
return dp[i][j];
// Since all numbers are unique and in range from 1 to n*n,
// there is atmost one possible direction from any cell
if (j<n-1 && ((mat[i][j] +1) == mat[i][j+1]))
return dp[i][j] = 1 + findLongestFromACell(i,j+1,mat,dp);
if (j>0 && (mat[i][j] +1 == mat[i][j-1]))
return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp);
if (i>0 && (mat[i][j] +1 == mat[i-1][j]))
return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp);
if (i<n-1 && (mat[i][j] +1 == mat[i+1][j]))
return dp[i][j] = 1 + findLongestFromACell(i+1,j,mat,dp);
// If none of the adjacent fours is one greater
return dp[i][j] = 1;
}
// Returns length of the longest path beginning with any cell
int finLongestOverAll(int mat[n][n])
{
int result = 1; // Initialize result
// Create a lookup table and fill all entries in it as -1
int dp[n][n];
memset(dp, -1, sizeof dp);
// Compute longest path beginning from all cells
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (dp[i][j] == -1)
findLongestFromACell(i, j, mat, dp);
717
Chapter 103. Find the longest path in a matrix with given constraints
Java
718
Chapter 103. Find the longest path in a matrix with given constraints
if (i>0 && (mat[i][j] +1 == mat[i-1][j]))
return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp);
if (i<n-1 && (mat[i][j] +1 == mat[i+1][j]))
return dp[i][j] = 1 + findLongestFromACell(i+1,j,mat,dp);
// If none of the adjacent fours is one greater
return dp[i][j] = 1;
}
// Function that returns length of the longest path
// beginning with any cell
static int finLongestOverAll(int mat[][])
{
// Initialize result
int result = 1;
// Create a lookup table and fill all entries in it as -1
int[][] dp = new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
dp[i][j] = -1;
// Compute longest path beginning from all cells
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (dp[i][j] == -1)
findLongestFromACell(i, j, mat, dp);
// Update result if needed
result = Math.max(result, dp[i][j]);
}
}
return result;
}
// driver program
public static void main (String[] args)
{
int mat[][] = { {1, 2, 9},
{5, 3, 8},
{4, 6, 7} };
System.out.println("Length of the longest path is " +
finLongestOverAll(mat));
719
Chapter 103. Find the longest path in a matrix with given constraints
}
}
// Contributed by Pramod Kumar
Output:
Time complexity of the above solution is O(n2 ). It may seem more at first look. If we take
a closer look, we can notice that all values of dp[i][j] are computed only once.
This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-the-longest-path-in-a-matrix-with-given-constraints/
720
Chapter 104
Approach:
Lets take a matrix mat of dimension 5×3 representing lengths, breadths, heights of 5
objects.
Now, the resulting mean vector will be a row vector of the following format :
Note: If we have a matrix of dimension M x N, then the resulting row vector will be
having dimension 1 x N
721
Chapter 104. Find the mean vector of a Matrix
Now, simply calculate the mean of each column of the matrix which will give the
required mean vector .
C++
722
Chapter 104. Find the mean vector of a Matrix
Java
723
Chapter 104. Find the mean vector of a Matrix
}
}
// This code is contributed
// by anuj_67.
Python3
724
Chapter 104. Find the mean vector of a Matrix
C#
// C# program to find
// mean vector of given matrix
using System;
class GFG
{
static int rows = 3;
static int cols = 3;
// Function to
// find mean vector
static void meanVector(int [,]mat)
{
Console.Write("[ ");
// loop to traverse
// each column
for (int i = 0; i < rows; i++)
{
// to calculate mean
// of each row
double mean = 0.00;
// to store sum of
// elements of a column
int sum = 0;
for (int j = 0; j < cols; j++)
sum += mat[j, i];
mean = sum / rows;
Console.Write((int)mean + " ");
}
Console.Write("]");
}
// Driver code
public static void Main ()
{
int[,] mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
meanVector(mat);
725
Chapter 104. Find the mean vector of a Matrix
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP program to find mean
// vector of given matrix
$rows = 3;
$cols = 3;
// Function to find mean vector
function meanVector($mat)
{
global $rows ,$cols;
echo "[ ";
// loop to traverse
// each column
for ($i = 0; $i < $rows; $i++)
{
// to calculate
// mean of each row
$mean = 0.00;
// to store sum of
// elements of a column
$sum = 0;
for ($j = 0; $j < $cols; $j++)
$sum += $mat[$j][$i];
$mean = $sum /$rows;
echo $mean , " ";
}
echo "]";
}
// Driver Code
$mat = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
726
Chapter 104. Find the mean vector of a Matrix
meanVector($mat);
// This code is contributed
// by anuj_6
?>
Output:
[ 4 5 6 ]
Source
https://www.geeksforgeeks.org/find-mean-vector-matrix/
727
Chapter 105
This is a variation of the standard problem: “Counting the number of connected components
in an undirected graph”.
Before we go to the problem, let us understand what is a connected component. A connected
component of an undirected graph is a subgraph in which every two vertices are connected
to each other by a path(s), and which is connected to no other vertices outside the subgraph.
For example, the graph shown below has three connected components.
728
Chapter 105. Find the number of islands | Set 1 (Using DFS)
A graph where all vertices are connected with each other has exactly one connected com-
ponent, consisting of the whole graph. Such graph with only one connected component is
called as Strongly Connected Graph.
The problem can be easily solved by applying DFS() on each component. In each DFS() call,
a component or a sub-graph is visited. We will call DFS on the next un-visited component.
The number of calls to DFS() gives the number of connected components. BFS can also be
used.
What is an island?
A group of connected 1s forms an island. For example, the below matrix contains 5 islands
{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
A cell in 2D matrix can be connected to 8 neighbours. So, unlike standard DFS(), where we
recursively call for all adjacent vertices, here we can recursively call for 8 neighbours only.
We keep track of the visited 1s so that they are not visited again.
C/C++
729
Chapter 105. Find the number of islands | Set 1 (Using DFS)
#define ROW 5
#define COL 5
// A function to check if a given cell (row, col) can be included in DFS
int isSafe(int M[][COL], int row, int col, bool visited[][COL])
{
// row number is in range, column number is in range and value is 1
// and not yet visited
return (row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL) &&
(M[row][col] && !visited[row][col]);
}
// A utility function to do DFS for a 2D boolean matrix. It only considers
// the 8 neighbours as adjacent vertices
void DFS(int M[][COL], int row, int col, bool visited[][COL])
{
// These arrays are used to get row and column numbers of 8 neighbours
// of a given cell
static int rowNbr[] = {-1, -1, -1, 0, 0, 1, 1, 1};
static int colNbr[] = {-1, 0, 1, -1, 1, -1, 0, 1};
// Mark this cell as visited
visited[row][col] = true;
// Recur for all connected neighbours
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited) )
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
// The main function that returns count of islands in a given boolean
// 2D matrix
int countIslands(int M[][COL])
{
// Make a bool array to mark visited cells.
// Initially all cells are unvisited
bool visited[ROW][COL];
memset(visited, 0, sizeof(visited));
// Initialize count as 0 and travese through the all cells of
// given matrix
int count = 0;
for (int i = 0; i < ROW; ++i)
for (int j = 0; j < COL; ++j)
if (M[i][j] && !visited[i][j]) // If a cell with value 1 is not
{ // visited yet, then new island found
730
Chapter 105. Find the number of islands | Set 1 (Using DFS)
Java
731
Chapter 105. Find the number of islands | Set 1 (Using DFS)
732
Chapter 105. Find the number of islands | Set 1 (Using DFS)
{1, 0, 1, 0, 1}
};
Islands I = new Islands();
System.out.println("Number of islands is: "+ I.countIslands(M));
}
} //Contributed by Aakash Hasija
Python
733
Chapter 105. Find the number of islands | Set 1 (Using DFS)
C#
// C# program to count
// islands in boolean
// 2D matrix
using System;
734
Chapter 105. Find the number of islands | Set 1 (Using DFS)
class GFG
{
// No of rows
// and columns
static int ROW = 5, COL = 5;
// A function to check if
// a given cell (row, col)
// can be included in DFS
static bool isSafe(int [,]M, int row,
int col, bool [,]visited)
{
// row number is in range,
// column number is in range
// and value is 1 and not
// yet visited
return (row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL) &&
(M[row, col] == 1 &&
!visited[row, col]);
}
// A utility function to do
// DFS for a 2D boolean matrix.
// It only considers the 8
// neighbors as adjacent vertices
static void DFS(int [,]M, int row,
int col, bool [,]visited)
{
// These arrays are used to
// get row and column numbers
// of 8 neighbors of a given cell
int []rowNbr = new int[] {-1, -1, -1, 0,
0, 1, 1, 1};
int []colNbr = new int[] {-1, 0, 1, -1,
1, -1, 0, 1};
// Mark this cell
// as visited
visited[row, col] = true;
// Recur for all
// connected neighbours
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col +
colNbr[k], visited))
DFS(M, row + rowNbr[k],
735
Chapter 105. Find the number of islands | Set 1 (Using DFS)
736
Chapter 105. Find the number of islands | Set 1 (Using DFS)
PHP
<?php
// Program to count islands
// in boolean 2D matrix
$ROW = 5;
$COL = 5;
// A function to check if a
// given cell (row, col) can
// be included in DFS
function isSafe(&$M, $row, $col,
&$visited)
{
global $ROW, $COL;
// row number is in range,
// column number is in
// range and value is 1
// and not yet visited
return ($row >= 0) && ($row < $ROW) &&
($col >= 0) && ($col < $COL) &&
($M[$row][$col] &&
!isset($visited[$row][$col]));
}
// A utility function to do DFS
// for a 2D boolean matrix. It
// only considers the 8 neighbours
// as adjacent vertices
function DFS(&$M, $row, $col,
&$visited)
{
// These arrays are used to
// get row and column numbers
// of 8 neighbours of a given cell
$rowNbr = array(-1, -1, -1, 0,
0, 1, 1, 1);
$colNbr = array(-1, 0, 1, -1,
1, -1, 0, 1);
// Mark this cell as visited
$visited[$row][$col] = true;
737
Chapter 105. Find the number of islands | Set 1 (Using DFS)
738
Chapter 105. Find the number of islands | Set 1 (Using DFS)
// This code is contributed
// by ChitraNayal
?>
Output:
Source
https://www.geeksforgeeks.org/find-number-of-islands/
739
Chapter 106
Example
Input matrix
0 1 1 1
0 0 1 1
1 1 1 1 // this row has maximum 1s
0 0 0 0
Output: 2
A simple method is to do a row wise traversal of the matrix, count the number of 1s in
each row and compare the count with max. Finally, return the index of row with maximum
1s. The time complexity of this method is O(m*n) where m is number of rows and n is
number of columns in matrix.
We can do better. Since each row is sorted, we can use Binary Search to count of 1s in
each row. We find the index of first instance of 1 in each row. The count of 1s will be equal
to total number of columns minus the index of first 1.
See the following code for implementation of the above approach.
C/C++
740
Chapter 106. Find the row with maximum number of 1s
#include <stdio.h>
#define R 4
#define C 4
// Function to find the index of first index
// of 1 in a boolean array arr[]
int first(bool arr[], int low, int high)
{
if(high >= low)
{
// Get the middle index
int mid = low + (high - low)/2;
// Check if the element at middle index is first 1
if ( ( mid == 0 || arr[mid-1] == 0) && arr[mid] == 1)
return mid;
// If the element is 0, recur for right side
else if (arr[mid] == 0)
return first(arr, (mid + 1), high);
// If element is not first 1, recur for left side
else
return first(arr, low, (mid -1));
}
return -1;
}
// Function that returns index of row
// with maximum number of 1s.
int rowWithMax1s(bool mat[R][C])
{
// Initialize max values
int max_row_index = 0, max = -1;
// Traverse for each row and count number of 1s
// by finding the index of first 1
int i, index;
for (i = 0; i < R; i++)
{
index = first (mat[i], 0, C-1);
if (index != -1 && C-index > max)
{
max = C - index;
max_row_index = i;
}
}
741
Chapter 106. Find the row with maximum number of 1s
return max_row_index;
}
// Driver Code
int main()
{
bool mat[R][C] = { {0, 0, 0, 1},
{0, 1, 1, 1},
{1, 1, 1, 1},
{0, 0, 0, 0}};
printf("Index of row with maximum 1s is %d "
, rowWithMax1s(mat));
return 0;
}
Java
742
Chapter 106. Find the row with maximum number of 1s
Python 3
743
Chapter 106. Find the row with maximum number of 1s
744
Chapter 106. Find the row with maximum number of 1s
Output:
// The main function that returns index of row with maximum number of 1s.
int rowWithMax1s(bool mat[R][C])
{
int i, index;
// Initialize max using values from first row.
int max_row_index = 0;
int max = first(mat[0], 0, C-1);
// Traverse for each row and count number of 1s by finding the index
// of first 1
for (i = 1; i < R; i++)
{
// Count 1s in this row only if this row has more 1s than
// max so far
// Count 1s in this row only if this row has more 1s than
// max so far
if (max != -1 && mat[i][C-max-1] == 1)
{
// Note the optimization here also
index = first (mat[i], 0, C-max);
if (index != -1 && C-index > max)
{
max = C - index;
max_row_index = i;
}
}
else {
max = first(mat[i], 0, C - 1);
}
}
return max_row_index;
}
745
Chapter 106. Find the row with maximum number of 1s
The worst case time complexity of the above optimized version is also O(mLogn), the will
solution work better on average. Thanks to Naveen Kumar Singh for suggesting the above
solution.
The worst case of the above solution occurs for a matrix like following.
000…01
0 0 0 ..0 1 1
0…0111
….0 1 1 1 1
Following method works in O(m+n) time complexity in worst case.
Step1: Get the index of first (or leftmost) 1 in the first row.
Step2: Do following for every row after the first row
…IF the element on left of previous leftmost 1 is 0, ignore this row.
…ELSE Move left until a 0 is found. Update the leftmost index to this index and
max_row_index to be the current row.
The time complexity is O(m+n) because we can possibly go as far left as we came ahead in
the first step.
Following is C++ implementation of this method.
// The main function that returns index of row with maximum number of 1s.
int rowWithMax1s(bool mat[R][C])
{
// Initialize first row as row with max 1s
int max_row_index = 0;
// The function first() returns index of first 1 in row 0.
// Use this index to initialize the index of leftmost 1 seen so far
int j = first(mat[0], 0, C-1);
if (j == -1) // if 1 is not present in first row
j = C - 1;
for (int i = 1; i < R; i++)
{
// Move left until a 0 is found
while (j >= 0 && mat[i][j] == 1)
{
j = j-1; // Update the index of leftmost 1 seen so far
max_row_index = i; // Update max_row_index
}
}
return max_row_index;
}
746
Chapter 106. Find the row with maximum number of 1s
Source
https://www.geeksforgeeks.org/find-the-row-with-maximum-number-1s/
747
Chapter 107
Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- GeeksforGeeks
Given two integers N and M. Consider two matrix ANXM , BNXM . Both matrix A and
matrix B contains elements from 1 to N*M. Matrix A contains elements in Row-major order
and matrix B contains elements in Column-major order. The task is to find the trace of the
matrix formed by addition of A and B. Trace of matrix PNXM is defined as P[0][0] + P[1][1]
+ P[2][2] +….. + P[min(n – 1, m – 1)][min(n – 1, m – 1)] i.e addition of main diagonal.
Note – Both matrix A and matrix B contains elements from 1 to N*M.
Examples :
Input : N = 3, M = 3
Output : 30
Therefore,
1 2 3
A = 4 5 6
7 8 9
1 4 7
B = 2 5 8
3 6 9
2 6 10
748
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
A + B = 6 10 14
10 14 18
Trace = 2 + 10 + 18 = 30
C++
749
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
// Finding the trace of matrix C.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j)
sum += C[i][j];
return sum;
}
// Driven Program
int main()
{
int N = 3, M = 3;
cout << trace(N, M) << endl;
return 0;
}
Java
750
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
C#
// C# program to find
// trace of matrix formed by
// adding Row-major and
// Column-major order of same matrix
using System;
class GFG {
// Return the trace of
// sum of row-major matrix
// and column-major matrix
static int trace(int n, int m)
{
int[, ] A = new int[n, m];
int[, ] B = new int[n, m];
751
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
Output :
30
752
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
1 2 3 4
A = 5 6 7 8
9 10 11 12
C++
753
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
Java
754
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
Python3
755
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
C#
756
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
PHP
<?php
// PHP program to find trace of matrix formed
// by adding Row-major and Column-major order
// of same matrix
// Return sum of first n integers of an AP
function sn($n, $an)
{
return ($n * (1 + $an)) / 2;
}
// Return the trace of sum
// of row-major matrix
// and column-major matrix
function trace($n, $m)
{
// Finding nth element in
// AP in case of Row major matrix.
$an = 1 + ($n - 1) * ($m + 1);
// Finding sum of first n integers
// of AP in case of Row major matrix
$rowmajorSum = sn($n, $an);
757
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix
Output :
30
Source
https://www.geeksforgeeks.org/find-trace-matrix-formed-adding-row-major-column-major-order-matrix/
758
Chapter 108
Input : 20 15 30 2
2 3 5 30
6 7 6 8
Output : 3 20 5 7 8 15
Input : 1 2 3
5 6 2
1 3 5
6 2 2
Output : No unique element in the matrix
759
Chapter 108. Find unique elements in a matrix
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
// function that calculate unique element
int unique(int mat[R][C], int n, int m)
{
int maximum = 0, flag = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
// Find maximum element in
// a matrix
if(maximum < mat[i][j])
maximum = mat[i][j];
// Take 1-D array of (maximum + 1)
// size
int b[maximum + 1] = {0};
for(int i = 0 ; i < n; i++)
for(int j = 0; j < m; j++)
b[mat[i][j]]++;
//print unique element
for(int i = 1; i <= maximum; i++)
if(b[i] == 1)
cout << i << " ";
flag = 1;
if(!flag){
cout << "No unique element in the matrix";
}
}
// Driver program
int main()
{
int mat[R][C] = {{ 1, 2, 3, 20},
{5, 6, 20, 25},
{1, 3, 5, 6},
{6, 7, 8, 15}};
// function that calculate unique
// element
unique(mat, R, C);
return 0;
}
760
Chapter 108. Find unique elements in a matrix
Java
761
Chapter 108. Find unique elements in a matrix
Python3
Output:
762
Chapter 108. Find unique elements in a matrix
2 7 8 25 15
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/find-unique-elements-matrix/
763
Chapter 109
Input : M[3][3] = {{ 0 , 3 , 2 },
{ 3 , 3 , 0 },
{ 1 , 3 , 0 }};
Output : Yes
Input : M[4][4] = {{ 0 , 3 , 1 , 0 },
{ 3 , 0 , 3 , 3 },
{ 2 , 3 , 0 , 3 },
{ 0 , 3 , 3 , 3 }};
Output : Yes
764
Chapter 109. Find whether there is path between two cells in matrix
Simple solution is that find the source index of cell in matrix and then recursively find a
path from source index to destination in matrix .
algorithm :
return false ;
765
Chapter 109. Find whether there is path between two cells in matrix
{
int V ;
list < int > *adj;
public :
Graph( int V )
{
this->V = V ;
adj = new list<int>[V];
}
void addEdge( int s , int d ) ;
bool BFS ( int s , int d) ;
};
// add edge to graph
void Graph :: addEdge ( int s , int d )
{
adj[s].push_back(d);
adj[d].push_back(s);
}
// BFS function to find path from source to sink
bool Graph :: BFS(int s, int d)
{
// Base case
if (s == d)
return true;
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and
// enqueue it
visited[s] = true;
queue.push_back(s);
// it will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while (!queue.empty())
{
// Dequeue a vertex from queue
s = queue.front();
766
Chapter 109. Find whether there is path between two cells in matrix
queue.pop_front();
// Get all adjacent vertices of the
// dequeued vertex s. If a adjacent has
// not been visited, then mark it visited
// and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
// If this adjacent node is the destination
// node, then return true
if (*i == d)
return true;
// Else, continue to do BFS
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
// If BFS is complete without visiting d
return false;
}
bool isSafe(int i, int j, int M[][N])
{
if ((i < 0 || i >= N) ||
(j < 0 || j >= N ) || M[i][j] == 0)
return false;
return true;
}
// Returns true if there is a path from a source (a
// cell with value 1) to a destination (a cell with
// value 2)
bool findPath(int M[][N])
{
int s , d ; // source and destination
int V = N*N+2;
Graph g(V);
// create graph with n*n node
// each cell consider as node
int k = 1 ; // Number of current vertex
for (int i =0 ; i < N ; i++)
{
767
Chapter 109. Find whether there is path between two cells in matrix
Output:
768
Chapter 109. Find whether there is path between two cells in matrix
Yes
Source
https://www.geeksforgeeks.org/find-whether-path-two-cells-matrix/
769
Chapter 110
Finding the maximum square sub-matrix with all equal elements - GeeksforGeeks
Given a N x N matrix, determine the maximum K such that K x K is a submatrix with all
equal elements i.e., all the elements in this submatrix must be same.
Constraints:
1 <= N <= 1000
0 <= Ai , j <= 109
Examples:
770
Chapter 110. Finding the maximum square sub-matrix with all equal elements
trix contains equal elements or not in O(n2 ) time Which makes the total running time of
the algorithm as O(n5 ).
Method II ( Dynamic Programming )
For each cell (i, j), we store the largest value of K such that K x K is a submatrix with all
equal elements and position of (i, j) being the bottom-right most element.
And DPi,j depends upon {DPi-1, j , DPi, j-1 , DPi-1, j-1 }
C++
771
Chapter 110. Finding the maximum square sub-matrix with all equal elements
{
// Check if adjacent elements are equal
if (a[i][j] == a[i-1][j] &&
a[i][j] == a[i][j-1] &&
a[i][j] == a[i-1][j-1] )
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]),
dp[i-1][j-1] ) + 1;
// If not equal, then it will form a 1x1
// submatrix
else dp[i][j] = 1;
}
// Update result at each (i,j)
result = max(result, dp[i][j]);
}
}
return result;
}
// Driven Program
int main()
{
int a[Row][Col] = { 2, 2, 3, 3, 4, 4,
5, 5, 7, 7, 7, 4,
1, 2, 7, 7, 7, 4,
4, 4, 7, 7, 7, 4,
5, 5, 5, 1, 2, 7,
8, 7, 9, 4, 4, 4
};
cout << largestKSubmatrix(a) << endl;
return 0;
}
Java
772
Chapter 110. Finding the maximum square sub-matrix with all equal elements
773
Chapter 110. Finding the maximum square sub-matrix with all equal elements
C#
774
Chapter 110. Finding the maximum square sub-matrix with all equal elements
else
{
// Check if adjacent
// elements are equal
if (a[i, j] == a[i - 1, j] &&
a[i, j] == a[i, j - 1] &&
a[i, j] == a[i - 1, j - 1])
{
dp[i, j] = (dp[i - 1, j] > dp[i, j - 1] &&
dp[i - 1, j] > dp[i - 1, j - 1] + 1) ?
dp[i - 1, j] :
(dp[i, j - 1] > dp[i - 1, j] &&
dp[i, j - 1] > dp[i - 1, j - 1] + 1) ?
dp[i, j - 1] :
dp[i - 1, j - 1] + 1;
}
// If not equal, then
// it will form a 1x1
// submatrix
else dp[i, j] = 1;
}
// Update result at each (i,j)
result = result > dp[i, j] ?
result : dp[i, j];
}
}
return result;
}
// Driver Code
public static void Main()
{
int[,] a = {{2, 2, 3, 3, 4, 4},
{5, 5, 7, 7, 7, 4},
{1, 2, 7, 7, 7, 4},
{4, 4, 7, 7, 7, 4},
{5, 5, 5, 1, 2, 7},
{8, 7, 9, 4, 4, 4}};
Console.Write(largestKSubmatrix(a));
}
}
// This code is contributed
// by ChitraNayal
775
Chapter 110. Finding the maximum square sub-matrix with all equal elements
Python 3
776
Chapter 110. Finding the maximum square sub-matrix with all equal elements
return result
# Driver Code
a = [[ 2, 2, 3, 3, 4, 4],
[ 5, 5, 7, 7, 7, 4],
[ 1, 2, 7, 7, 7, 4],
[ 4, 4, 7, 7, 7, 4],
[ 5, 5, 5, 1, 2, 7],
[ 8, 7, 9, 4, 4, 4]];
print(largestKSubmatrix(a))
# This code is contributed
# by ChitraNayal
PHP
<?php
// Java program to find maximum
// K such that K x K is a
// submatrix with equal elements.
$Row = 6;
$Col = 6;
// Returns size of the largest
// square sub-matrix with
// all same elements.
function largestKSubmatrix(&$a)
{
global $Row, $Col;
$result = 0;
for ($i = 0 ;
$i < $Row ; $i++)
{
for ($j = 0 ;
$j < $Col ; $j++)
{
// If elements is at
// top row or first
// column, it wont form
// a square matrix's
// bottom-right
if ($i == 0 || $j == 0)
$dp[$i][$j] = 1;
else
{
777
Chapter 110. Finding the maximum square sub-matrix with all equal elements
Output:
778
Chapter 110. Finding the maximum square sub-matrix with all equal elements
Source
https://www.geeksforgeeks.org/finding-the-maximum-square-sub-matrix-with-all-equal-elements/
779
Chapter 111
Input:
screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
x = 4, y = 4, newColor = 3
The values in the given 2D screen indicate colors of the pixels.
x and y are coordinates of the brush, newColor is the color that
should replace the previous color on screen[x][y] and all surrounding
pixels with same color.
Output:
Screen should be changed to following.
screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
780
Chapter 111. Flood fill Algorithm – how to implement fill() in paint?
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 3, 3, 3, 3, 0, 1, 0},
{1, 1, 1, 3, 3, 0, 1, 0},
{1, 1, 1, 3, 3, 3, 3, 0},
{1, 1, 1, 1, 1, 3, 1, 1},
{1, 1, 1, 1, 1, 3, 3, 1},
};
781
Chapter 111. Flood fill Algorithm – how to implement fill() in paint?
// Recur for north, east, south and west
floodFillUtil(screen, x+1, y, prevC, newC);
floodFillUtil(screen, x-1, y, prevC, newC);
floodFillUtil(screen, x, y+1, prevC, newC);
floodFillUtil(screen, x, y-1, prevC, newC);
}
// It mainly finds the previous color on (x, y) and
// calls floodFillUtil()
void floodFill(int screen[][N], int x, int y, int newC)
{
int prevC = screen[x][y];
floodFillUtil(screen, x, y, prevC, newC);
}
// Driver program to test above function
int main()
{
int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
int x = 4, y = 4, newC = 3;
floodFill(screen, x, y, newC);
cout << "Updated screen after call to floodFill: n";
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
cout << screen[i][j] << " ";
cout << endl;
}
}
Output:
782
Chapter 111. Flood fill Algorithm – how to implement fill() in paint?
1 1 1 3 3 3 3 0
1 1 1 1 1 3 1 1
1 1 1 1 1 3 3 1
References:
http://en.wikipedia.org/wiki/Flood_fill
This article is contributed by Anmol. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/flood-fill-algorithm-implement-fill-paint/
783
Chapter 112
Input : n = 1;
Output : Coil 1 : 10 6 2 3 4 8 12 16
Coil 2 : 7 11 15 14 13 9 5 1
Explanation : Matrix is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input : n = 2;
Output : Coil 1 : 36 28 20 21 22 30 38 46 54
53 52 51 50 42 34 26 18 10
2 3 4 5 6 7 8 16 24 32 40
48 56 64
Coil 2 : 29 37 45 44 43 35 27 19 11 12
13 14 15 23 31 39 47 55 63 62
61 60 59 58 57 49 41 33 25 17
9 1
Total elements in matrix are 16n2 . All elements are divided in two coils. Every coil has 8n2
elements. We make two arrays of this size. We first fill elements in coil1 by traversing in
given order. Once we have filled elements in coil1, we can get elements of other coil2 using
formula coil2[i] = 16*n*n + 1 -coil1[i].
784
Chapter 112. Form coils in a matrix
C++
785
Chapter 112. Form coils in a matrix
step += 2;
}
/* get coil2 from coil1 */
int coil2[m];
for (int i=0; i<8*n*n; i++)
coil2[i] = 16*n*n + 1 -coil1[i];
// Print both coils
cout << "Coil 1 : ";
for(int i=0; i<8*n*n; i++)
cout << coil1[i] << " ";
cout << "\nCoil 2 : ";
for (int i=0; i<8*n*n; i++)
cout << coil2[i] << " ";
}
// Driver code
int main()
{
int n = 1;
printCoils(n);
return 0;
}
Java
786
Chapter 112. Form coils in a matrix
787
Chapter 112. Form coils in a matrix
{
int n = 1;
printCoils(n);
}
}
// This code is contributed by Anant Agarwal.
C#
788
Chapter 112. Form coils in a matrix
curr = coil1[index++]
= (curr - 4 * n * nflg);
if (index >= m)
break;
}
if (index >= m)
break;
// Fill elements of current step
// from up to down.
for (int i = 0; i < step; i++)
{
curr = coil1[index++] = curr
+ nflg;
if (index >= m)
break;
}
nflg = nflg * (-1);
step += 2;
}
/* get coil2 from coil1 */
int [] coil2 = new int[m];
for (int i = 0; i < 8 * n * n; i++)
coil2[i] = 16 * n * n + 1 - coil1[i];
// Print both coils
Console.Write("Coil 1 : ");
for (int i = 0; i < 8 * n * n; i++)
Console.Write(coil1[i] + " ");
Console.Write("\nCoil 2 : ");
for (int i = 0; i < 8 * n * n; i++)
Console.Write(coil2[i] + " ");
}
// Driver code
public static void Main()
{
int n = 1;
printCoils(n);
789
Chapter 112. Form coils in a matrix
}
}
// This code is contributed by KRV.
PHP
<?php
// PHP program to print 2 coils of a
// 4n x 4n matrix.
// Print coils in a matrix of size 4n x 4n
function printCoils( $n)
{
// Number of elements in each coil
$m = 8 * $n * $n;
// Let us fill elements in coil 1.
$coil1 = array();
// First element of coil1
// 4*n*2*n + 2*n;
$coil1[0] = 8 * $n * $n + 2 * $n;
$curr = $coil1[0];
$nflg = 1; $step = 2;
// Fill remaining m-1 elements in coil1[]
$index = 1;
while ($index < $m)
{
// Fill elements of current step from
// down to up
for ( $i = 0; $i < $step; $i++)
{
// Next element from current element
$curr = $coil1[$index++] =
($curr - 4*$n*$nflg);
if ($index >= $m)
break;
}
if ($index >= $m)
break;
// Fill elements of current step from
// up to down.
for ( $i=0; $i<$step; $i++)
790
Chapter 112. Form coils in a matrix
{
$curr = $coil1[$index++] =
$curr + $nflg;
if ($index >= $m)
break;
}
$nflg = $nflg * (-1);
$step += 2;
}
/* get coil2 from coil1 */
$coil2 = array();
for ( $i = 0; $i < 8 * $n * $n; $i++)
$coil2[$i] = 16 * $n * $n + 1 -$coil1[$i];
// Print both coils
echo "Coil 1 : ";
for( $i = 0; $i < 8 * $n * $n; $i++)
echo $coil1[$i] , " ";
echo "\nCoil 2 : ";
for ( $i = 0; $i < 8 * $n * $n; $i++)
echo $coil2[$i] , " ";
}
// Driver code
$n = 1;
printCoils($n);
// This code is contributed by anuj_67.
?>
Output:
Coil 1 : 10 6 2 3 4 8 12 16
Coil 2 : 7 11 15 14 13 9 5 1
Asked in Yahoo
Improved By : KRV, vt_m
791
Chapter 112. Form coils in a matrix
Source
https://www.geeksforgeeks.org/form-coils-matrix/
792
Chapter 113
Input : A = 1 1
1 1
B = 1 1
1 1
C = 2 2
2 2
Output : Yes
C = A x B
Input : A = 1 1 1
1 1 1
1 1 1
B = 1 1 1
1 1 1
1 1 1
C = 3 3 3
3 1 2
3 3 3
Output : No
A simple solution is to find product of A and B and then check if product is equal to
C or not. A possible time complexity of this method is O(n2.8874 ) using Stression’s matrix
multiplication.
793
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
The idea is based on the fact that if C is actually a product, then value of A × (Br)�– Cr�
will always be 0. If the value is non-zero, then C can not be a product. The error condition
is that the value may be 0 even when C is not a product.
C++
794
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
Java
795
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
static int N = 2;
// Function to check if ABx = Cx
static boolean freivald(int a[][], int b[][],
int c[][])
{
// Generate a random vector
int r[] = new int[N];
for (int i = 0; i < N; i++)
r[i] = (int)(Math.random()) % 2;
// Now comput B*r for evaluating
// expression A * (B*r) - (C*r)
int br[] = new int[N];
Arrays.fill(br, 0);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
br[i] = br[i] + b[i][j] * r[j];
// Now comput C*r for evaluating
// expression A * (B*r) - (C*r)
int cr[] = new int[N];
Arrays.fill(cr, 0);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
cr[i] = cr[i] + c[i][j] * r[j];
// Now comput A* (B*r) for evaluating
// expression A * (B*r) - (C*r)
int axbr[] = new int[N];
Arrays.fill(axbr, 0);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
axbr[i] = axbr[i] + a[i][j] * br[j];
// Finally check if value of expression
// A * (B*r) - (C*r) is 0 or not
for (int i = 0; i < N; i++)
if (axbr[i] - cr[i] != 0)
return false;
return true;
}
// Runs k iterations Freivald. The value
// of k determines accuracy. Higher value
// means higher accuracy.
static boolean isProduct(int a[][], int b[][],
796
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
Python3
797
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
C#
// C# code to implement
// Freivald's Algorithm
798
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
using System;
class GFG
{
static int N = 2;
// Function to check
// if ABx = Cx
static bool freivald(int [,]a,
int [,]b,
int [,]c)
{
// Generate a
// random vector
Random rand = new Random();
int []r = new int[N];
for (int i = 0; i < N; i++)
r[i] = (int)(rand.Next()) % 2;
// Now compute B*r for
// evaluating expression
// A * (B*r) - (C*r)
int []br = new int[N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
br[i] = br[i] +
b[i, j] * r[j];
// Now compute C*r for
// evaluating expression
// A * (B*r) - (C*r)
int []cr = new int[N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
cr[i] = cr[i] +
c[i, j] * r[j];
// Now compute A* (B*r) for
// evaluating expression
// A * (B*r) - (C*r)
int []axbr = new int[N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
axbr[i] = axbr[i] +
799
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
a[i, j] * br[j];
// Finally check if value
// of expression A * (B*r) -
// (C*r) is 0 or not
for (int i = 0; i < N; i++)
if (axbr[i] - cr[i] != 0)
return false;
return true;
}
// Runs k iterations Freivald.
// The value of k determines
// accuracy. Higher value
// means higher accuracy.
static bool isProduct(int [,]a, int [,]b,
int [,]c, int k)
{
for (int i = 0; i < k; i++)
if (freivald(a, b, c) == false)
return false;
return true;
}
// Driver code
static void Main()
{
int [,]a = new int[,]{ { 1, 1 },
{ 1, 1 }};
int [,]b = new int[,]{ { 1, 1 },
{ 1, 1 }};
int [,]c = new int[,]{ { 2, 2 },
{ 2, 2 }};
int k = 2;
if (isProduct(a, b, c, k))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by Manish Shaw(manishshaw1)
PHP
<?php
// PHP code to implement
800
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
// Freivald’s Algorithm
$N = 2;
// Function to check
// if ABx = Cx
function freivald($a, $b, $c)
{
global $N;
// Generate a
// random vector
$r = array();
$br = array();
$cr = array();
$axbr = array();
for ($i = 0; $i < $N; $i++)
{
$r[$i] = mt_rand() % 2;
$br[$i] = 0;
$cr[$i] = 0;
$axbr[$i] = 0;
}
// Now comput B*r for
// evaluating expression
// A * (B*r) - (C*r)
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
$br[$i] = $br[$i] +
$b[$i][$j] *
$r[$j];
}
// Now comput C*r for
// evaluating expression
// A * (B*r) - (C*r)
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
$cr[$i] = $cr[$i] +
$c[$i][$j] *
$r[$j];
}
// Now comput A* (B*r) for
// evaluating expression
801
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
802
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two
?>
Output:
Yes
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/freivalds-algorithm/
803
Chapter 114
Input : m = 3, n = 3
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
Output : Frequency of odd number = 5
Frequency of even number = 4
Input : m = 3, n = 3
{ 10, 11, 12 },
{ 13, 14, 15 },
{ 16, 17, 18 }
Output : Frequency of odd number = 4
Frequency of even number = 5
CPP
804
Chapter 114. Frequencies of even and odd numbers in a matrix
Java
805
Chapter 114. Frequencies of even and odd numbers in a matrix
Python3
806
Chapter 114. Frequencies of even and odd numbers in a matrix
C#
807
Chapter 114. Frequencies of even and odd numbers in a matrix
else
++odd;
}
}
// print Frequency of numbers
Console.WriteLine(" Frequency of odd number =" +
odd );
Console.WriteLine(" Frequency of even number = " +
even );
}
// Driver code
public static void Main()
{
int m = 3, n = 3;
int [,]array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
freq(array, m, n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to Find the frequency
// of even and odd numbers in a matrix
$MAX = 100;
// function for calculating frequency
function freq($ar, $m, $n)
{
$even = 0; $odd = 0;
for($i = 0; $i < $m; ++$i)
{
for ( $j = 0; $j < $n; ++$j)
{
// modulo by 2 to check
// even and odd
if (($ar[$i][$j] % 2) == 0)
++$even;
else
++$odd;
}
}
808
Chapter 114. Frequencies of even and odd numbers in a matrix
// print Frequency of numbers
echo " Frequency of odd number = "
, $odd,"\n";
echo " Frequency of even number = "
, $even;
}
// Driver code
$m = 3; $n = 3;
$array = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
freq($array, $m, $n);
// This code is contributed by anuj_67.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-frequency-even-odd-numbers-matrix/
809
Chapter 115
Given 1’s, 2’s, 3’s ......k’s print them in zig zag way. - GeeksforGeeks
Given number of rows and columns. And given number of 1’s, 2’s, 3’s ……k’s which needs to
be printed. Print them in a zig-zag way.
It is guaranteed that n*m = number of 1’s + 2’s + 3’s + …… + k’s
Examples:
Input : 2 3
2 1 2 1
Output : 1 1 2
4 3 3
Explanation :
Here number of rows are 2 and number of columns are 3
and number of 1's are 2
number of 2's are 1
number of 3's are 2
number of 4's are 1
-----------
| 1 | 1 | 2 |
| 3 | 3 | 4 |
-----------
Input : 4 3
2 4 3 1 2
Output : 1 1 2
2 2 2
3 3 3
5 5 4
810
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
Explanation :
Here number of rows are 4 and number of columns are 3
and number of 1's are 2
number of 2's are 4 [Note that 2s are printed in]
number of 3's are 3 [zig zag manner]
number of 4's are 1
number of 5's are 2
Approach: We make a two-dimensional array to store all the elements in zig-zag way. we
will traverse through all the elements of array of numbers and insert all the numbers of
array of i-th index into two-dimensional array until it becomes zero.
C++
811
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
if (numbers[k] == 0)
k++;
}
}
// for odd row.
else
{
// for each column.
for (int j=columns-1; j>=0 and
numbers[k]>0; j--)
{
// storing element.
arr[i][j] = k+1;
// decrement element
// at kth index.
numbers[k]--;
// if array contains zero then
// increment index to make this
// next index.
if (numbers[k]==0)
k++;
}
}
}
// printing the stored elements.
for (int i=0;i<rows;i++)
{
for (int j=0;j<columns;j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
// Driver code for above function.
int main()
{
int rows = 4;
int columns = 5;
int Numbers[] = {3, 4, 2, 2, 3, 1, 5};
ZigZag(rows, columns, Numbers);
return 0;
}
812
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
Java
813
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
C#
814
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
using System;
public class GfG{
// function that prints given number of 1's,
// 2's, 3's ....k's in zig-zag way.
public static void ZigZag(int rows,
int columns,
int []numbers)
{
int k = 0;
// two-dimensional array to store numbers.
int[,] arr = new int[rows,columns];
for (int i = 0; i < rows; i++)
{
// for even row.
if (i % 2 == 0)
{
// for each column.
for (int j = 0; j < columns &&
numbers[k] > 0; j++)
{
// storing element.
arr[i,j] = k + 1;
// decrement element at
// kth index.
numbers[k]--;
// if array contains zero
// then increment index to
// make this next index
if (numbers[k] == 0)
k++;
}
}
// for odd row.
else
{
// for each column.
for (int j = columns - 1; j >= 0 &&
numbers[k] > 0; j--)
{
// storing element.
arr[i,j] = k + 1;
815
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
// decrement element
// at kth index.
numbers[k]--;
// if array contains zero then
// increment index to make this
// next index.
if (numbers[k] == 0)
k++;
}
}
}
// printing the stored elements.
for (int i = 0;i < rows; i++)
{
for (int j = 0; j < columns; j++)
Console.Write(arr[i, j] + " ");
Console.WriteLine();
}
}
// Driver function
public static void Main()
{
int rows = 4;
int columns = 5;
int []Numbers = new int[]{3, 4, 2,
2, 3, 1, 5};
ZigZag(rows, columns, Numbers);
}
}
/* This code is contributed by vt_m*/
PHP
<?php
// PHP program to print given number of 1's,
// 2's, 3's ....k's in zig-zag way.
// function that prints given number of 1's,
// 2's, 3's ....k's in zig-zag way.
function ZigZag($rows, $columns, $numbers)
{
$k = 0;
816
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
// two-dimensional array
// to store numbers.
$arr = array(array());
for($i = 0; $i < $rows; $i++)
{
// for even row.
if ($i % 2==0)
{
// for each column.
for($j = 0; $j < $columns and
$numbers[$k] > 0; $j++)
{
// storing element.
$arr[$i][$j] = $k + 1;
// decrement element at
// kth index.
$numbers[$k]--;
// if array contains zero
// then increment index to
// make this next index
if ($numbers[$k] == 0)
$k++;
}
}
// for odd row.
else
{
// for each column.
for($j = $columns - 1; $j >= 0 and
$numbers[$k] > 0; $j--)
{
// storing element.
$arr[$i][$j] = $k + 1;
// decrement element
// at kth index.
$numbers[$k]--;
817
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.
Output:
1 1 1 2 2
4 3 3 2 2
4 5 5 5 6
7 7 7 7 7
Improved By : vt_m
Source
https://www.geeksforgeeks.org/given-1s-2s-3s-ks-print-zig-zag-way/
818
Chapter 116
Given a Boolean Matrix, find k such that all elements in k’th row are 0 and k’th column
are 1. - GeeksforGeeks
Given a square boolean matrix mat[n][n], find k such that all elements in k’th row are 0 and
all elements in k’th column are 1. The value of mat[k][k] can be anything (either 0 or 1). If
no such k exists, return -1.
Examples:
819
Chapter 116. Given a Boolean Matrix, find k such that all elements in k’th row are 0 and
k’th column are 1.
.........If all left side elements of i'th row are not 0, them this row cannot
.........be a solution, increment i.
820
Chapter 116. Given a Boolean Matrix, find k such that all elements in k’th row are 0 and
k’th column are 1.
.........If all elements of j'th column are not 1, them this column cannot be a
.........solution decrement j.
// C++ program to find i such that all entries in i'th row are 0
// and all entries in i't column are 1
#include <iostream>
using namespace std;
#define n 5
int find(bool arr[n][n])
{
// Start from top-most rightmost corner
// (We could start from other corners also)
int i=0, j=n-1;
// Initialize result
int res = -1;
// Find the index (This loop runs at most 2n times, we either
// increment row number or decrement column number)
while (i<n && j>=0)
{
// If current element is 0, then this row may be a solution
if (arr[i][j] == 0)
{
// Check for all elements in this row
while (j >= 0 && (arr[i][j] == 0 || i == j))
j--;
// If all values are 0, then store this row as result
if (j == -1)
{
res = i;
break;
}
// We reach here if we found a 1 in current row, so this
// row cannot be a solution, increment row number
821
Chapter 116. Given a Boolean Matrix, find k such that all elements in k’th row are 0 and
k’th column are 1.
else i++;
}
else // If current element is 1
{
// Check for all elements in this column
while (i<n && (arr[i][j] == 1 || i == j))
i++;
// If all elements are 1
if (i == n)
{
res = j;
break;
}
// We reach here if we found a 0 in current column, so this
// column cannot be a solution, increment column number
else j--;
}
}
// If we could not find result in above loop, then result doesn't exist
if (res == -1)
return res;
// Check if above computed res is valid
for (int i=0; i<n; i++)
if (res != i && arr[i][res] != 1)
return -1;
for (int j=0; j<n; j++)
if (res != j && arr[res][j] != 0)
return -1;
return res;
}
/* Driver program to test above functions */
int main()
{
bool mat[n][n] = {{0, 0, 1, 1, 0},
{0, 0, 0, 1, 0},
{1, 1, 1, 1, 0},
{0, 0, 0, 0, 0},
{1, 1, 1, 1, 1}};
cout << find(mat);
return 0;
822
Chapter 116. Given a Boolean Matrix, find k such that all elements in k’th row are 0 and
k’th column are 1.
Python
''' Python program to find k such that all elements in k'th row
are 0 and k'th column are 1'''
def find(arr):
# store length of the array
n = len(arr)
# start from top right-most corner
i = 0
j = n - 1
# initialise result
res = -1
# find the index (This loop runs at most 2n times, we
# either increment row number or decrement column number)
while i < n and j >= 0:
# if the current element is 0, then this row may be a solution
if arr[i][j] == 0:
# check for all the elements in this row
while j >= 0 and (arr[i][j] == 0 or i == j):
j -= 1
# if all values are 0, update result as row number
if j == -1:
res = i
break
# if found a 1 in current row, the row can't be a
# solution, increment row number
else: i += 1
# if the current element is 1
else:
#check for all the elements in this column
while i < n and (arr[i][j] == 1 or i == j):
i +=1
# if all elements are 1, update result as col number
if i == n:
823
Chapter 116. Given a Boolean Matrix, find k such that all elements in k’th row are 0 and
k’th column are 1.
res = j
break
# if found a 0 in current column, the column can't be a
# solution, decrement column number
else: j -= 1
# if we couldn't find result in above loop, result doesn't exist
if res == -1:
return res
# check if the above computed res value is valid
for i in range(0, n):
if res != i and arr[i][res] != 1:
return -1
for j in range(0, j):
if res != j and arr[res][j] != 0:
return -1;
return res;
# test find(arr) function
arr = [ [0,0,1,1,0],
[0,0,0,1,0],
[1,1,1,1,0],
[0,0,0,0,0],
[1,1,1,1,1] ]
print find(arr)
Output:
Time complexity of this solution is O(n). Note that we traverse at most 2n elements in the
main while loop.
This article is contributed by Ashish Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-k-such-that-all-elements-in-kth-row-are-0-and-kth-column-are-1-in-a-boolean-
824
Chapter 117
Given a matrix of ‘O’ and ‘X’, replace ’O’ with ’X’ if surrounded by ’X’ - GeeksforGeeks
Given a matrix where every element is either ‘O’ or ‘X’, replace ‘O’ with ‘X’ if surrounded
by ‘X’. A ‘O’ (or a set of ‘O’) is considered to be by surrounded by ‘X’ if there are ‘X’ at
locations just below, just above, just left and just right of it.
Examples:
825
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
This is mainly an application of Flood-Fill algorithm. The main difference here is that a
‘O’ is not replaced by ‘X’ if it lies in region that ends on a boundary. Following are simple
steps to do this special flood fill.
1) Traverse the given matrix and replace all ‘O’ with a special character ‘-‘.
2) Traverse four edges of given matrix and call floodFill(‘-‘, ‘O’) for every ‘-‘ on edges. The
remaining ‘-‘ are the characters that indicate ‘O’s (in the original matrix) to be replaced by
‘X’.
3) Traverse the matrix and replace all ‘-‘s with ‘X’s.
Let us see steps of above algorithm with an example. Let following be the
input matrix.
Step 2: Call floodFill(‘-‘, ‘O’) for all edge elements with value equals to ‘-‘
826
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
827
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
828
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
return 0;
}
Java
829
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
static void replaceSurrounded(char mat[][])
{
// Step 1: Replace
// all 'O' with '-'
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] == 'O')
mat[i][j] = '-';
// Call floodFill for
// all '-' lying on edges
for (int i = 0; i < M; i++) // Left side
if (mat[i][0] == '-')
floodFillUtil(mat, i, 0,
'-', 'O');
for (int i = 0; i < M; i++) // Right side
if (mat[i][N - 1] == '-')
floodFillUtil(mat, i, N - 1,
'-', 'O');
for (int i = 0; i < N; i++) // Top side
if (mat[0][i] == '-')
floodFillUtil(mat, 0, i,
'-', 'O');
for (int i = 0; i < N; i++) // Bottom side
if (mat[M - 1][i] == '-')
floodFillUtil(mat, M - 1,
i, '-', 'O');
// Step 3: Replace
// all '-' with 'X'
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] == '-')
mat[i][j] = 'X';
}
// Driver Code
public static void main (String[] args)
{
char[][] mat = {{'X', 'O', 'X',
'O', 'X', 'X'},
{'X', 'O', 'X',
'X', 'O', 'X'},
830
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
C#
// A C# program to replace
// all 'O's with 'X''s if
// surrounded by 'X'
using System;
class GFG
{
static int M = 6;
static int N = 6;
static void floodFillUtil(char [,]mat, int x,
int y, char prevV,
char newV)
{
// Base cases
if (x < 0 || x >= M ||
y < 0 || y >= N)
return;
if (mat[x, y] != prevV)
return;
// Replace the color at (x, y)
831
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
mat[x, y] = newV;
// Recur for north,
// east, south and west
floodFillUtil(mat, x + 1, y,
prevV, newV);
floodFillUtil(mat, x - 1, y,
prevV, newV);
floodFillUtil(mat, x, y + 1,
prevV, newV);
floodFillUtil(mat, x, y - 1,
prevV, newV);
}
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
static void replaceSurrounded(char [,]mat)
{
// Step 1: Replace
// all 'O' with '-'
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (mat[i, j] == 'O')
mat[i, j] = '-';
// Call floodFill for
// all '-' lying on edges
for (int i = 0; i < M; i++) // Left side
if (mat[i, 0] == '-')
floodFillUtil(mat, i, 0,
'-', 'O');
for (int i = 0; i < M; i++) // Right side
if (mat[i, N - 1] == '-')
floodFillUtil(mat, i, N - 1,
'-', 'O');
for (int i = 0; i < N; i++) // Top side
if (mat[0, i] == '-')
floodFillUtil(mat, 0, i,
'-', 'O');
for (int i = 0; i < N; i++) // Bottom side
if (mat[M - 1, i] == '-')
floodFillUtil(mat, M - 1,
i, '-', 'O');
// Step 3: Replace
// all '-' with 'X'
832
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
PHP
<?php
// A PHP program to replace all
// 'O's with 'X''s if surrounded by 'X'
// Size of given
// matrix is M X N
$M = 6;
$N = 6;
833
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
// A recursive function to replace
// previous value 'prevV' at '(x, y)'
// and all surrounding values of
// (x, y) with new value 'newV'.
function floodFillUtil(&$mat, $x, $y,
$prevV, $newV)
{
// Base cases
if ($x < 0 || $x >= $GLOBALS['M'] ||
$y < 0 || $y >= $GLOBALS['N'])
return;
if ($mat[$x][$y] != $prevV)
return;
// Replace the color at (x, y)
$mat[$x][$y] = $newV;
// Recur for north,
// east, south and west
floodFillUtil($mat, $x + 1, $y, $prevV, $newV);
floodFillUtil($mat, $x - 1, $y, $prevV, $newV);
floodFillUtil($mat, $x, $y + 1, $prevV, $newV);
floodFillUtil($mat, $x, $y - 1, $prevV, $newV);
}
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
function replaceSurrounded(&$mat)
{
// Step 1: Replace all 'O' with '-'
for ($i = 0; $i < $GLOBALS['M']; $i++)
for ($j = 0; $j < $GLOBALS['N']; $j++)
if ($mat[$i][$j] == 'O')
$mat[$i][$j] = '-';
// Call floodFill for all
// '-' lying on edges
for ($i = 0;
$i < $GLOBALS['M']; $i++) // Left side
if ($mat[$i][0] == '-')
floodFillUtil($mat, $i, 0, '-', 'O');
for ($i = 0; $i < $GLOBALS['M']; $i++) // Right side
if ($mat[$i][$GLOBALS['N'] - 1] == '-')
834
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
floodFillUtil($mat, $i,
$GLOBALS['N'] - 1, '-', 'O');
for ($i = 0; $i < $GLOBALS['N']; $i++) // Top side
if ($mat[0][$i] == '-')
floodFillUtil($mat, 0, $i, '-', 'O');
for ($i = 0; $i < $GLOBALS['N']; $i++) // Bottom side
if ($mat[$GLOBALS['M'] - 1][$i] == '-')
floodFillUtil($mat, $GLOBALS['M'] - 1,
$i, '-', 'O');
// Step 3: Replace all '-' with 'X'
for ($i = 0; $i < $GLOBALS['M']; $i++)
for ($j = 0; $j < $GLOBALS['N']; $j++)
if ($mat[$i][$j] == '-')
$mat[$i][$j] = 'X';
}
// Driver Code
$mat = array(array('X', 'O', 'X', 'O', 'X', 'X'),
array('X', 'O', 'X', 'X', 'O', 'X'),
array('X', 'X', 'X', 'O', 'X', 'X'),
array('O', 'X', 'X', 'X', 'X', 'X'),
array('X', 'X', 'X', 'O', 'X', 'O'),
array('O', 'O', 'X', 'O', 'O', 'O'));
replaceSurrounded($mat);
for ($i = 0; $i < $GLOBALS['M']; $i++)
{
for ($j = 0; $j < $GLOBALS['N']; $j++)
echo $mat[$i][$j]." ";
echo "\n";
}
// This code is contributed by ChitraNayal
?>
Output:
X O X O X X
X O X X X X
X X X X X X
O X X X X X
X X X O X O
O O X O O O
835
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
Time Complexity of the above solution is O(MN). Note that every element of matrix is
processed at most three times.
This article is contributed by Anmol. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Improved By : shiv_bhakt, ChitraNayal
Source
https://www.geeksforgeeks.org/given-matrix-o-x-replace-o-x-surrounded-x/
836
Chapter 118
Given a matrix of ’O’ and ’X’, find the largest subsquare surrounded by ’X’ - GeeksforGeeks
Given a matrix where every element is either ‘O’ or ‘X’, find the largest subsquare surrounded
by ‘X’.
In the below article, it is assumed that the given matrix is also square matrix. The code
given below can be easily extended for rectangular matrices.
Examples:
837
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
A Simple Solution is to consider every square submatrix and check whether is has all
corner edges filled with ‘X’. The time complexity of this solution is O(N4 ).
We can solve this problem in O(N3 ) time using extra space. The idea is to create two
auxiliary arrays hor[N][N] and ver[N][N]. The value stored in hor[i][j] is the number of hori-
zontal continuous ‘X’ characters till mat[i][j] in mat[][]. Similarly, the value stored in ver[i][j]
is the number of vertical continuous ‘X’ characters till mat[i][j] in mat[][]. Following is an
example.
mat[6][6] = X O X X X X
X O X X O X
X X X O O X
O X X X X X
X X X O X O
O O X O O O
hor[6][6] = 1 0 1 2 3 4
1 0 1 2 0 1
1 2 3 0 0 1
0 1 2 3 4 5
1 2 3 0 1 0
0 0 1 0 0 0
ver[6][6] = 1 0 1 1 1 1
2 0 2 2 0 2
3 1 3 0 0 3
0 2 4 1 1 4
1 3 5 0 2 0
0 0 6 0 0 0
Once we have filled values in hor[][] and ver[][], we start from the bottommost-rightmost
corner of matrix and move toward the leftmost-topmost in row by row manner. For every
visited entry mat[i][j], we compare the values of hor[i][j] and ver[i][j], and pick the smaller
of two as we need a square. Let the smaller of two be ‘small’. After picking smaller of two,
we check if both ver[][] and hor[][] for left and up edges respectively. If they have entries for
the same, then we found a subsquare. Otherwise we try for small-1.
Below is implementation of the above idea.
C++
838
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
#include<iostream>
using namespace std;
// Size of given matrix is N X N
#define N 6
// A utility function to find minimum of two numbers
int getMin(int x, int y) { return (x<y)? x: y; }
// Returns size of maximum size subsquare matrix
// surrounded by 'X'
int findSubSquare(int mat[][N])
{
int max = 0; // Initialize result
// Initialize the left-top value in hor[][] and ver[][]
int hor[N][N], ver[N][N];
hor[0][0] = ver[0][0] = (mat[0][0] == 'X');
// Fill values in hor[][] and ver[][]
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
if (mat[i][j] == 'O')
ver[i][j] = hor[i][j] = 0;
else
{
hor[i][j] = (j==0)? 1: hor[i][j-1] + 1;
ver[i][j] = (i==0)? 1: ver[i-1][j] + 1;
}
}
}
// Start from the rightmost-bottommost corner element and find
// the largest ssubsquare with the help of hor[][] and ver[][]
for (int i = N-1; i>=1; i--)
{
for (int j = N-1; j>=1; j--)
{
// Find smaller of values in hor[][] and ver[][]
// A Square can only be made by taking smaller
// value
int small = getMin(hor[i][j], ver[i][j]);
// At this point, we are sure that there is a right
// vertical line and bottom horizontal line of length
// at least 'small'.
839
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
// We found a bigger square if following conditions
// are met:
// 1)If side of square is greater than max.
// 2)There is a left vertical line of length >= 'small'
// 3)There is a top horizontal line of length >= 'small'
while (small > max)
{
if (ver[i][j-small+1] >= small &&
hor[i-small+1][j] >= small)
{
max = small;
}
small--;
}
}
}
return max;
}
// Driver program to test above function
int main()
{
int mat[][N] = {{'X', 'O', 'X', 'X', 'X', 'X'},
{'X', 'O', 'X', 'X', 'O', 'X'},
{'X', 'X', 'X', 'O', 'O', 'X'},
{'O', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'O'},
{'O', 'O', 'X', 'O', 'O', 'O'},
};
cout << findSubSquare(mat);
return 0;
}
Java
840
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
841
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
842
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
// by ChitraNayal
PHP
<?php
// A PHP program to find
// the largest subsquare
// surrounded by 'X' in a
// given matrix of 'O' and 'X'
// Size of given
// matrix is N X N
$N = 6;
// A utility function to find
// minimum of two numbers
function getMin($x, $y)
{
return ($x < $y) ? $x : $y;
}
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
function findSubSquare($mat)
{
$max = 0; // Initialize result
$hor[0][0] = $ver[0][0] = ($mat[0][0] == 'X');
// Fill values in
// $hor and $ver
for ($i = 0; $i < $GLOBALS['N']; $i++)
{
for ($j = 0; $j < $GLOBALS['N']; $j++)
{
if ($mat[$i][$j] == 'O')
$ver[$i][$j] = $hor[$i][$j] = 0;
else
{
$hor[$i][$j] = ($j == 0) ? 1 :
$hor[$i][$j - 1] + 1;
$ver[$i][$j] = ($i == 0) ? 1 :
$ver[$i - 1][$j] + 1;
}
}
}
// Start from the rightmost-
843
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
844
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
Output:
This article is contributed by Anuj. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : ChitraNayal, Suryaveer Singh
Source
https://www.geeksforgeeks.org/given-matrix-o-x-find-largest-subsquare-surrounded-x/
845
Chapter 119
Input:
n = 5, k = 3
arr[][] = { {1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5},
};
Output:
18 18 18
27 27 27
36 36 36
Input:
n = 3, k = 2
arr[][] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
846
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
Output:
12 16
24 28
A Simple Solution is to one by one pick starting point (leftmost-topmost corner) of all
possible sub-squares. Once the starting point is picked, calculate sum of sub-square starting
with the picked starting point.
Following is the implementation of this idea.
C++
847
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
Java
848
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
C#
849
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
PHP
<?php
// A simple PHP program to find
// sum of all subsquares of size
// k x k
// Size of given matrix
$n = 5;
// function to find sum of all sub -
// squares of size k x k in a given
// square matrix of size n x n
850
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
851
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
Output:
18 18 18
27 27 27
36 36 36
Time complexity of above solution is O(k2 n2 ). We can solve this problem in O(n2 ) time
using a Tricky Solution. The idea is to preprocess the given square matrix. In the
preprocessing step, calculate sum of all vertical strips of size k x 1 in a temporary square
matrix stripSum[][]. Once we have sum of all vertical strips, we can calculate sum of first
sub-square in a row as sum of first k strips in that row, and for remaining sub-squares, we
can calculate sum in O(1) time by removing the leftmost strip of previous subsquare and
adding the rightmost strip of new square.
Following is the implementation of this idea.
C++
852
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
Java
853
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
class GFG {
// Size of given matrix
static int n = 5;
// A O(n^2) function to find sum of all
// sub-squares of size k x k in a given
// square matrix of size n x n
static void printSumTricky(int mat[][], int k) {
// k must be smaller than or equal to n
if (k > n)
return;
// 1: PREPROCESSING
// To store sums of all strips of size k x 1
int stripSum[][] = new int[n][n];
// Go column by column
for (int j = 0; j < n; j++) {
// Calculate sum of first k x 1
// rectangle in this column
int sum = 0;
for (int i = 0; i < k; i++)
sum += mat[i][j];
stripSum[0][j] = sum;
// Calculate sum of remaining rectangles
for (int i = 1; i < n - k + 1; i++) {
sum += (mat[i + k - 1][j] - mat[i - 1][j]);
stripSum[i][j] = sum;
}
}
// 2: CALCULATE SUM of Sub-Squares
// using stripSum[][]
for (int i = 0; i < n - k + 1; i++) {
// Calculate and print sum of first
// subsquare in this row
int sum = 0;
for (int j = 0; j < k; j++)
sum += stripSum[i][j];
System.out.print(sum + " ");
// Calculate sum of remaining squares
854
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
C#
855
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
856
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
PHP
<?php
// An efficient PHP program to
// find sum of all subsquares
// of size k x k
// Size of given matrix
$n = 5;
// A O(n^2) function to find
// sum of all sub-squares of
// size k x k in a given
// square matrix of size n x n
function printSumTricky($mat, $k)
{
global $n;
// k must be smaller
// than or equal to n
if ($k > $n) return;
// 1: PREPROCESSING
// To store sums of all
// strips of size k x 1
$stripSum = array(array());
857
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
// Go column by column
for ($j = 0; $j < $n; $j++)
{
// Calculate sum of first
// k x 1 rectangle in this column
$sum = 0;
for ($i = 0; $i < $k; $i++)
$sum += $mat[$i][$j];
$stripSum[0][$j] = $sum;
// Calculate sum of
// remaining rectangles
for ($i = 1; $i < $n - $k + 1; $i++)
{
$sum += ($mat[$i + $k - 1][$j] -
$mat[$i - 1][$j]);
$stripSum[$i][$j] = $sum;
}
}
// 2: CALCULATE SUM of
// Sub-Squares using stripSum[][]
for ($i = 0; $i < $n - $k + 1; $i++)
{
// Calculate and print sum of
// first subsquare in this row
$sum = 0;
for ($j = 0; $j < $k; $j++)
$sum += $stripSum[$i][$j];
echo $sum , " ";
// Calculate sum of remaining
// squares in current row by
// removing the leftmost strip
// of previous sub-square and
// adding a new strip
for ($j = 1; $j < $n - $k + 1; $j++)
{
$sum += ($stripSum[$i][$j + $k - 1] -
$stripSum[$i][$j - 1]);
echo $sum , " ";
}
echo "\n";
}
}
858
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k
// Driver Code
$mat = array(array(1, 1, 1, 1, 1),
array(2, 2, 2, 2, 2),
array(3, 3, 3, 3, 3),
array(4, 4, 4, 4, 4),
array(5, 5, 5, 5, 5));
$k = 3;
printSumTricky($mat, $k);
// This code is contributed by anuj_67.
?>
Output :
18 18 18
27 27 27
36 36 36
This article is contributed by Rahul Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Sam007, nitin mittal, vt_m
Source
https://www.geeksforgeeks.org/given-n-x-n-square-matrix-find-sum-sub-squares-size-k-x-k/
859
Chapter 120
860
Chapter 120. Gold Mine Problem
Create a 2-D matrix goldTable[][]) of the same as given matrix mat[][]. If we observe the
question closely, we can notice following.
If we are at the first row or last column, then we are unable to move right-up so just assign
0 otherwise assign the value of goldTable[row-1][col+1] to right_up. If we are at the last
row or last column, then we are unable to move right down so just assign 0 otherwise assign
the value of goldTable[row+1][col+1] to right up.
Now find the maximum of right, right_up, and right_down and then add it with that
mat[row][col]. At last, find the maximum of all rows and first column and return it.
CPP
861
Chapter 120. Gold Mine Problem
goldTable[row+1][col+1];
// Max gold collected from taking either of the
// above 3 paths
goldTable[row][col] = gold[row][col] +
max(right, max(right_up, right_down));
}
}
// The max amount of gold collected will be the max
// value in first column of all rows
int res = goldTable[0][0];
for (int i=1; i<m; i++)
res = max(res, goldTable[i][0]);
return res;
}
// Driver Code
int main()
{
int gold[MAX][MAX]= { {1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2}
};
int m = 4, n = 4;
cout << getMaxGold(gold, m, n);
return 0;
}
Java
862
Chapter 120. Gold Mine Problem
863
Chapter 120. Gold Mine Problem
return res;
}
//driver code
public static void main(String arg[])
{
int gold[][]= { {1, 3, 1, 5},
{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2} };
int m = 4, n = 4;
System.out.print(getMaxGold(gold, m, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
864
Chapter 120. Gold Mine Problem
865
Chapter 120. Gold Mine Problem
Output:
16
Source
https://www.geeksforgeeks.org/gold-mine-problem/
866
Chapter 121
Hilbert Matrix
1. It is a symmetric matrix.
2. Its determinant value is always positive.
Source
https://www.geeksforgeeks.org/hilbert-matrix/
867
Chapter 122
Input:
1 2 3
4 5 6
7 8 9
Output:
1 6 7
2 5 8
3 4 9
At first look, the problem seems similar to finding transpose of the matrix. But if you
look carefully, you will notice that every even column in output matrix has elements of
corresponding row in input matrix in opposite order.
We strongly recommend you to minimize your browser and try this yourself first.
The problem can be easily converted to transpose of the matrix by doing some modification
to the input matrix. If we invert every even row present in input matrix, we can use solution
given here to convert the matrix in desired order and that too without using any auxiliary
memory.
Below is C++ implementation of the idea.
868
Chapter 122. In-place convert matrix in specific order
869
Chapter 122. In-place convert matrix in specific order
}
// A utility function to print a 2D array of size
// nr x nc and base address A
void Print2DArray(int *A, int nr, int nc)
{
for (int r = 0; r < nr; r++)
{
for (int c = 0; c < nc; c++)
printf("%4d", *(A + r*nc + c));
printf("\n");
}
printf("\n");
}
// Driver program to test above function
int main(void)
{
int A[][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int r = 3, c = 4;
cout << "Given Matrix:\n";
Print2DArray((int *)A, r, c);
transformMatrix((int *)A, r, c);
cout << "Transformed Matrix:\n";
Print2DArray((int *)A, c, r);
return 0;
}
Output:
Given Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Transformed Matrix:
1 8 9
2 7 10
870
Chapter 122. In-place convert matrix in specific order
3 6 11
4 5 12
Source
https://www.geeksforgeeks.org/in-place-convert-matrix-in-specific-order/
871
Chapter 123
a b c a d g j
d e f ==> b e h k
g h i c f i l
j k l
872
Chapter 123. Inplace (Fixed space) M x N size matrix transpose | Updated
Note that the first and last elements stay in their original location. We can easily see
the transformation forms few permutation cycles.
From the above example, we can easily devise an algorithm to move the elements along
these cycles. How can we generate permutation cycles? Number of elements in both the
matrices are constant, given by N = R * C, where R is row count and C is column count.
An element at location ol (old location in R x C matrix), moved to nl (new location in C x
R matrix). We need to establish relation between ol, nl, R and C. Assume ol = A[or][oc].
In C/C++ we can calculate the element address as,
nl = oc x R + or -----> [eq 1]
ol = or x C + oc
ol x R = or x C x R + oc x R
= or x N + oc x R (from the fact R * C = N)
= or x N + (nl - or) --- from [eq 1]
= or x (N-1) + nl
OR,
nl = ol x R - or x (N-1)
Note that the values of nl and ol never go beyond N-1, so considering modulo division on
both the sides by (N-1), we get the following based on properties of congruence,
873
Chapter 123. Inplace (Fixed space) M x N size matrix transpose | Updated
A curious reader might have observed the significance of above relation. Every
location is scaled by a factor of R (row size). It is obvious from the matrix that
every location is displaced by scaled factor of R. The actual multiplier depends
on congruence class of (N-1), i.e. the multiplier can be both -ve and +ve value
of the congruent class.Hence every location transformation is simple modulo division.
These modulo divisions form cyclic permutations. We need some book keeping information
to keep track of already moved elements. Here is code for inplace matrix transformation,
874
Chapter 123. Inplace (Fixed space) M x N size matrix transpose | Updated
{
// Input matrix [r x c]
// Output matrix
// i_new = (i*r)%(N-1)
next = (i*r)%size;
swap(A[next], t);
b[i] = 1;
i = next;
}
while (i != cycleBegin);
// Get Next Move (what about querying random location?)
for (i = 1; i < size && b[i]; i++)
;
cout << endl;
}
}
// Driver program to test above function
int main(void)
{
int r = 5, c = 6;
int size = r*c;
int *A = new int[size];
for(int i = 0; i < size; i++)
A[i] = i+1;
Print2DArray(A, r, c);
MatrixInplaceTranspose(A, r, c);
Print2DArray(A, c, r);
delete[] A;
return 0;
}
Output:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
1 7 13 19 25
2 8 14 20 26
3 9 15 21 27
875
Chapter 123. Inplace (Fixed space) M x N size matrix transpose | Updated
4 10 16 22 28
5 11 17 23 29
6 12 18 24 30
Extension: 17 – March – 2013 Some readers identified similarity between the matrix
transpose and string transformation. Without much theory I am presenting the problem
and solution. In given array of elements like [a1b2c3d4e5f6g7h8i9j1k2l3m4]. Convert it
to [abcdefghijklm1234567891234]. The program should run inplace. What we need is an
inplace transpose. Given below is code.
#include <stdio.h>
#include <iostream>
#include <bitset>
#define HASH_SIZE 128
using namespace std;
typedef char data_t;
void Print2DArray(char A[], int nr, int nc) {
int size = nr*nc;
for(int i = 0; i < size; i++)
printf("%4c", *(A + i));
printf("\n");
}
void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) {
int size = r*c - 1;
data_t t; // holds element to be replaced, eventually becomes next element to move
int next; // location of 't' to be moved
int cycleBegin; // holds start of cycle
int i; // iterator
bitset<HASH_SIZE> b; // hash to mark moved elements
b.reset();
b[0] = b[size] = 1;
i = 1; // Note that A[0] and A[size-1] won't move
while( i < size ) {
cycleBegin = i;
t = A[i];
do {
// Input matrix [r x c]
// Output matrix
// i_new = (i*r)%size
next = (i*r)%size;
swap(A[next], t);
b[i] = 1;
876
Chapter 123. Inplace (Fixed space) M x N size matrix transpose | Updated
i = next;
} while( i != cycleBegin );
// Get Next Move (what about querying random location?)
for(i = 1; i < size && b[i]; i++)
;
cout << endl;
}
}
void Fill(data_t buf[], int size) {
// Fill abcd ...
for(int i = 0; i < size; i++)
buf[i] = 'a'+i;
// Fill 0123 ...
buf += size;
for(int i = 0; i < size; i++)
buf[i] = '0'+i;
}
void TestCase_01(void) {
int r = 2, c = 10;
int size = r*c;
data_t *A = new data_t[size];
Fill(A, c);
Print2DArray(A, r, c), cout << endl;
MatrixTransposeInplaceArrangement(A, r, c);
Print2DArray(A, c, r), cout << endl;
delete[] A;
}
int main() {
TestCase_01();
return 0;
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Update 09-July-2016: Notes on space complexity and storage order.
After long time, it happened to review this post. Some readers pointed valid questions on
how can it be in-place (?) when we are using bitset as marker (hash in code). Apologies
for incorrect perception by looking at the article heading or content. While preparing
the initial content, I was thinking of naive implementation using auxiliary space of atleast
877
Chapter 123. Inplace (Fixed space) M x N size matrix transpose | Updated
O(MN) needed to transpose rectangualr matrix. The program presented above is using
constant space as bitset size is fixed at compile time. However, to support arbitrary size
of matrices we need bitset size atleast O(MN) size. One can use a HashMap (amortized
O(1) complexity) for marking finished locations, yet HashMap’s worst case complexity can
be O(N) or O(log N) based on implementation. HashMap space cost also increases based
on items inserted. Please note that in-place was used w.r.t. matrix space.
Also, it was assumed that the matrix will be stored in row major ordering (contigueous
locations in memory). The reader can derive the formulae, if the matrix is represented in
column major order by the programming language (e.g. Fortran/Julia).
Thanks to the readers who pointed these two gaps.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
The post is incomplete without mentioning two links.
1. Aashish covered good theory behind cycle leader algorithm. See his post on string
transformation.
2. As usual, Sambasiva demonstrated his exceptional skills in recursion to the problem.
Ensure to understand his solution.
— Venki. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Source
https://www.geeksforgeeks.org/inplace-m-x-n-size-matrix-transpose/
878
Chapter 124
Input
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
879
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
880
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
1 5 9 13
881
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
// assign temp to left
mat[N-1-y][x] = temp;
}
}
}
// Function to print the matrix
void displayMatrix(int mat[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf("%2d ", mat[i][j]);
printf("\n");
}
printf("\n");
}
/* Driver program to test above functions */
int main()
{
// Test Case 1
int mat[N][N] =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// Tese Case 2
/* int mat[N][N] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
*/
// Tese Case 3
/*int mat[N][N] = {
{1, 2},
{4, 5}
};*/
882
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
//displayMatrix(mat);
rotateMatrix(mat);
// Print rotated matrix
displayMatrix(mat);
return 0;
}
Java
883
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(" " + mat[i][j]);
System.out.print("\n");
}
System.out.print("\n");
}
/* Driver program to test above functions */
public static void main (String[] args)
{
int N = 4;
// Test Case 1
int mat[][] =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// Tese Case 2
/* int mat[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
*/
// Tese Case 3
/*int mat[][] = {
{1, 2},
{4, 5}
};*/
// displayMatrix(mat);
rotateMatrix(N,mat);
// Print rotated matrix
displayMatrix(N,mat);
}
}
884
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
// This code is contributed by Prakriti Gupta
Python3
885
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
# Driver Code
mat = [[0 for x in range(N)] for y in range(N)]
# Test case 1
mat = [ [1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12 ],
[13, 14, 15, 16 ] ]
'''
# Test case 2
mat = [ [1, 2, 3 ],
[4, 5, 6 ],
[7, 8, 9 ] ]
# Test case 3
mat = [ [1, 2 ],
[4, 5 ] ]
'''
rotateMatrix(mat)
# Print rotated matrix
displayMatrix(mat)
# This code is contributed by saloni1297
C#
// C# program to rotate a
// matrix by 90 degrees
using System;
class GFG
{
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in anti-
// clockwise direction
static void rotateMatrix(int N,
int [,]mat)
{
// Consider all
// squares one by one
for (int x = 0; x < N / 2; x++)
886
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
{
// Consider elements
// in group of 4 in
// current square
for (int y = x; y < N - x - 1; y++)
{
// store current cell
// in temp variable
int temp = mat[x, y];
// move values from
// right to top
mat[x, y] = mat[y, N - 1 - x];
// move values from
// bottom to right
mat[y, N - 1 - x] = mat[N - 1 - x,
N - 1 - y];
// move values from
// left to bottom
mat[N - 1 - x,
N - 1 - y] = mat[N - 1 - y, x];
// assign temp to left
mat[N - 1 - y, x] = temp;
}
}
}
// Function to print the matrix
static void displayMatrix(int N,
int [,]mat)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
Console.Write(" " + mat[i, j]);
Console.WriteLine();
}
Console.WriteLine();
}
// Driver Code
static public void Main ()
{
int N = 4;
887
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
PHP
<?php
// PHP program to rotate a
// matrix by 90 degrees
$N = 4;
// An Inplace function to
// rotate a N x N matrix
// by 90 degrees in
// anti-clockwise direction
888
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
function rotateMatrix(&$mat)
{
global $N;
// Consider all
// squares one by one
for ($x = 0; $x < $N / 2; $x++)
{
// Consider elements
// in group of 4 in
// current square
for ($y = $x;
$y < $N - $x - 1; $y++)
{
// store current cell
// in temp variable
$temp = $mat[$x][$y];
// move values from
// right to top
$mat[$x][$y] = $mat[$y][$N - 1 - $x];
// move values from
// bottom to right
$mat[$y][$N - 1 - $x] =
$mat[$N - 1 - $x][$N - 1 - $y];
// move values from
// left to bottom
$mat[$N - 1 - $x][$N - 1 - $y] =
$mat[$N - 1 - $y][$x];
// assign temp to left
$mat[$N - 1 - $y][$x] = $temp;
}
}
}
// Function to
// print the matrix
function displayMatrix(&$mat)
{
global $N;
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
echo $mat[$i][$j] . " ";
889
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
echo "\n";
}
echo "\n";
}
// Driver code
// Test Case 1
$mat = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 10, 11, 12),
array(13, 14, 15, 16));
// Tese Case 2
/* $mat = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
*/
// Tese Case 3
/*$mat = array(array(1, 2),
array(4, 5));*/
// displayMatrix($mat);
rotateMatrix($mat);
// Print rotated matrix
displayMatrix($mat);
// This code is contributed
// by ChitraNayal
?>
Output :
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Exercise: Turn 2D matrix by 90 degrees in clockwise direction without using extra space.
Rotate a matrix by 90 degree without using any extra space | Set 2
Improved By : jit_t, ChitraNayal
890
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1
Source
https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/
891
Chapter 125
Input : 3 4 5 0
2 6 1 2
2 7 1 2
2 1 1 2
Output : 2 1 1 2
2 7 1 2
2 6 1 2
3 4 5 0
Input : 9 7 5 1
2 3 4 1
5 6 6 5
1 2 3 1
Output : 1 2 3 1
2 3 4 1
5 6 6 5
9 7 5 1
The approach is very simple, we can simply swap the elements of first and last row of the
matrix inorder to get the desired matrix as output.
Below is the implementation of the approach :
892
Chapter 125. Interchange elements of first and last rows in matrix
C++
Java
893
Chapter 125. Interchange elements of first and last rows in matrix
Python3
894
Chapter 125. Interchange elements of first and last rows in matrix
Output :
9 9 7 7
4 7 6 5
3 2 1 8
8 9 7 6
Improved By : shrikanth13
Source
https://www.geeksforgeeks.org/interchange-elements-of-first-and-last-rows-in-matrix/
895
Chapter 126
Examples :
Input : A = 1 2 B = 0 5
3 4 6 7
Output : C = 0 5 0 10
6 7 12 14
0 15 0 20
18 21 24 28
896
Chapter 126. Kronecker Product of two matrices
Input : A = 1 2 B = 0 5 2
3 4 6 7 3
1 0
Output : C = 0 5 2 0 10 4
6 7 3 12 14 6
0 15 6 0 20 8
18 21 9 24 28 12
0 5 2 0 0 0
6 7 3 0 0 0
Below is the code to find the Kronecker Product of two matrices and stores it as matrix C :
897
Chapter 126. Kronecker Product of two matrices
// Each element of matrix A is
// multiplied by whole Matrix B
// resp and stored as Matrix C
C[i + l + 1][j + k + 1] = A[i][j] * B[k][l];
printf("%d\t", C[i + l + 1][j + k + 1]);
}
}
printf("\n");
}
}
}
// Driver Code
int main()
{
int A[3][2] = { { 1, 2 }, { 3, 4 }, { 1, 0 } },
B[2][3] = { { 0, 5, 2 }, { 6, 7, 3 } };
Kroneckerproduct(A, B);
return 0;
}
Java
898
Chapter 126. Kronecker Product of two matrices
// k loops till rowb
for (int k = 0; k < rowb; k++)
{
// j loops till cola
for (int j = 0; j < cola; j++)
{
// l loops till colb
for (int l = 0; l < colb; l++)
{
// Each element of matrix A is
// multiplied by whole Matrix B
// resp and stored as Matrix C
C[i + l + 1][j + k + 1] = A[i][j] * B[k][l];
System.out.print( C[i + l + 1][j + k + 1]+" ");
}
}
System.out.println();
}
}
}
// Diver program
public static void main (String[] args)
{
int A[][] = { { 1, 2 },
{ 3, 4 },
{ 1, 0 } };
int B[][] = { { 0, 5, 2 },
{ 6, 7, 3 } };
Kroneckerproduct(A, B);
}
}
// This code is contributed by Gitanjali.
Python3
899
Chapter 126. Kronecker Product of two matrices
900
Chapter 126. Kronecker Product of two matrices
B[0][0] = 0
B[0][1] = 5
B[0][2] = 2
B[1][0] = 6
B[1][1] = 7
B[1][2] = 3
Kroneckerproduct( A , B )
# This code is contributed by Saloni.
C#
901
Chapter 126. Kronecker Product of two matrices
{
// Each element of matrix A is
// multiplied by whole Matrix B
// resp and stored as Matrix C
C[i + l + 1, j + k + 1] = A[i, j] *
B[k, l];
Console.Write( C[i + l + 1,
j + k + 1] + " ");
}
}
Console.WriteLine();
}
}
}
// Diver Code
public static void Main ()
{
int [,]A = {{1, 2},
{3, 4},
{1, 0}};
int [,]B = {{0, 5, 2},
{6, 7, 3}};
Kroneckerproduct(A, B);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP code to find the
// Kronecker Product of two
// rowa and cola are no of
// rows and columns of matrix A
// rowb and colb are no of
// rows and columns of matrix B
$cola = 2;
$rowa = 3;
$colb = 3;
$rowb = 2;
// Function to computes the
902
Chapter 126. Kronecker Product of two matrices
903
Chapter 126. Kronecker Product of two matrices
Kroneckerproduct($A, $B);
// This code is contributed by ajit
?>
Output :
0 5 2 0 10 4
6 7 3 12 14 6
0 15 6 0 20 8
18 21 9 24 28 12
0 5 2 0 0 0
6 7 3 0 0 0
Source
https://www.geeksforgeeks.org/kronecker-product-two-matrices/
904
Chapter 127
We have discussed one implementation of Kruskal’s algorithm in previous post. In this post,
a simpler implementation for adjacency matrix is discussed.
905
Chapter 127. Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
}
// Does union of i and j. It returns
// false if i and j are already in same
// set.
void union1(int i, int j)
{
int a = find(i);
int b = find(j);
parent[a] = b;
}
// Finds MST using Kruskal's algorithm
void kruskalMST(int cost[][V])
{
int mincost = 0; // Cost of min MST.
// Initialize sets of disjoint sets.
for (int i = 0; i < V; i++)
parent[i] = i;
// Include minimum weight edges one by one
int edge_count = 0;
while (edge_count < V - 1) {
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (find(i) != find(j) && cost[i][j] < min) {
min = cost[i][j];
a = i;
b = j;
}
}
}
union1(a, b);
printf("Edge %d:(%d, %d) cost:%d \n",
edge_count++, a, b, min);
mincost += min;
}
printf("\n Minimum cost= %d \n", mincost);
}
// driver program to test above function
int main()
{
/* Let us create the following graph
2 3
906
Chapter 127. Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix)
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int cost[][V] = {
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};
// Print the solution
kruskalMST(cost);
return 0;
}
Output:
Minimum cost= 16
Note that the above solution is not efficient. The idea is to provide a simple implementation
for adjacency matrix representations. Please see below for efficient implementations.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Kruskal’s Minimum Spanning Tree using STL in C++
Source
https://www.geeksforgeeks.org/kruskals-algorithm-simple-implementation-for-adjacency-matrix/
907
Chapter 128
Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1 - GeeksforGeeks
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Find
the kth smallest element in the given 2D array.
For example, consider the following 2D array.
908
Chapter 128. Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
#include<climits>
using namespace std;
// A structure to store an entry of heap. The entry contains
// a value from 2D array, row and column numbers of the value
struct HeapNode {
int val; // value to be stored
int r; // Row number of value in 2D array
int c; // Column number of value in 2D array
};
// A utility function to swap two HeapNode items.
void swap(HeapNode *x, HeapNode *y) {
HeapNode z = *x;
*x = *y;
*y = z;
}
// A utility function to minheapify the node harr[i] of a heap
// stored in harr[]
void minHeapify(HeapNode harr[], int i, int heap_size)
{
int l = i*2 + 1;
int r = i*2 + 2;
int smallest = i;
if (l < heap_size && harr[l].val < harr[i].val)
smallest = l;
if (r < heap_size && harr[r].val < harr[smallest].val)
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
minHeapify(harr, smallest, heap_size);
}
}
// A utility function to convert harr[] to a max heap
void buildHeap(HeapNode harr[], int n)
{
int i = (n - 1)/2;
while (i >= 0)
{
minHeapify(harr, i, n);
i--;
}
}
// This function returns kth smallest element in a 2D array mat[][]
909
Chapter 128. Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
Output:
910
Chapter 128. Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1
Source
https://www.geeksforgeeks.org/kth-smallest-element-in-a-row-wise-and-column-wise-sorted-2d-array-set-1/
911
Chapter 129
Largest area rectangular sub-matrix with equal number of 1’s and 0’s - GeeksforGeeks
Given a binary matrix. The problem is to find the largest area rectangular sub-matrix with
equal number of 1’s and 0’s.
Examples:
The naive solution for this problem is to check every possible rectangle in given 2D array
by counting the total number of 1’s and 0’s in that rectangle. This solution requires 4 nested
loops and time complexity of this solution would be O(n^4).
An efficient solution is based on Largest rectangular sub-matrix whose sum is 0 which
reduces the time complexity to O(n^3). First of all consider every ‘0’ in the matrix as ‘-1’.
Now, the idea is to reduce the problem to 1-D array. We fix the left and right columns one
by one and find the largest sub-array with 0 sum contiguous rows for every left and right
912
Chapter 129. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
column pair. We basically find top and bottom row numbers (which have sum zero) for
every fixed left and right column pair. To find the top and bottom row numbers, calculate
sum of elements in every row from left to right and store these sums in an array say temp[].
So temp[i] indicates sum of elements from left to right in row i. If we find largest subarray
with 0 sum in temp[], we can get the index positions of rectangular sub-matrix with sum
equal to 0 (i.e. having equal number of 1’s and 0’s). With this process we can find the
largest area rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s
and 0’s). We can use Hashing technique to find maximum length sub-array with sum equal
to 0 in 1-D array in O(n) time.
913
Chapter 129. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
914
Chapter 129. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
// to store the final outputs
int finalLeft, finalRight, finalTop, finalBottom;
finalLeft = finalRight = finalTop = finalBottom = -1;
int maxArea = 0;
// Set the left column
for (int left = 0; left < col; left++)
{
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column
// set by outer loop
for (int right = left; right < col; right++)
{
// Calculate sum between current left
// and right for every row 'i'
// consider value '1' as '1' and
// value '0' as '-1'
for (int i=0; i<row; i++)
temp[i] += mat[i][right] ? 1 : -1;
// Find largest subarray with 0 sum in
// temp[]. The subArrWithSumZero() function
// also sets values of finalTop, finalBottom,
// finalLeft and finalRight if there exists
// a subarray with sum 0 in temp
if (subArrWithSumZero(temp, startRow, endRow, row))
{
int area = (right - left + 1) *
(endRow - startRow + 1);
// Compare current 'area' with previous area
// and accodingly update final values
if (maxArea < area)
{
finalTop = startRow;
finalBottom = endRow;
finalLeft = left;
finalRight = right;
maxArea = area;
}
}
}
}
// if true then there is no rectangular submatrix
915
Chapter 129. Largest area rectangular sub-matrix with equal number of 1’s and 0’s
Output:
Source
https://www.geeksforgeeks.org/largest-area-rectangular-sub-matrix-equal-number-1s-0s/
916
Chapter 130
Input :
917
Chapter 130. Largest connected component on a grid
Approach :
The approach is to visualize the given grid as a graph with each cell representing a separate
node of the graph and each node connected to four other nodes which are to immediately
up, down, left, and right of that grid. Now doing a BFS search for every node of the graph,
find all the nodes connected to the current node with same color value as the current node.
Here is the graph for above example :
918
Chapter 130. Largest connected component on a grid
C++
919
Chapter 130. Largest connected component on a grid
// stores information about which cell
// are already visited in a particular BFS
int visited[n][m];
// result stores the final result grid
int result[n][m];
// stores the count of cells in the largest
// connected component
int COUNT;
// Function checks if a cell is valid i.e it
// is inside the grid and equal to the key
bool is_valid(int x, int y, int key, int input[n][m])
{
if (x < n && y < m && x >= 0 && y >= 0) {
if (visited[x][y] == false && input[x][y] == key)
return true;
else
return false;
}
else
return false;
}
// BFS to find all cells in
// connection with key = input[i][j]
void BFS(int x, int y, int i, int j, int input[n][m])
{
// terminating case for BFS
if (x != y)
return;
visited[i][j] = 1;
COUNT++;
// x_move and y_move arrays
// are the possible movements
// in x or y direction
int x_move[] = { 0, 0, 1, -1 };
int y_move[] = { 1, -1, 0, 0 };
// checks all four points connected with input[i][j]
for (int u = 0; u < 4; u++)
if (is_valid(i + y_move[u], j + x_move[u], x, input))
BFS(x, y, i + y_move[u], j + x_move[u], input);
}
920
Chapter 130. Largest connected component on a grid
// called every time before a BFS
// so that visited array is reset to zero
void reset_visited()
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
visited[i][j] = 0;
}
// If a larger connected component
// is found this function is called
// to store information about that component.
void reset_result(int key, int input[n][m])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (visited[i][j] && input[i][j] == key)
result[i][j] = visited[i][j];
else
result[i][j] = 0;
}
}
}
// function to print the result
void print_result(int res)
{
cout << "The largest connected "
<< "component of the grid is :" << res << "\n";
// prints the largest component
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (result[i][j])
cout << result[i][j] << " ";
else
cout << ". ";
}
cout << "\n";
}
}
// function to calculate the largest connected
// component
void computeLargestConnectedGrid(int input[n][m])
{
int current_max = INT_MIN;
921
Chapter 130. Largest connected component on a grid
Java
922
Chapter 130. Largest connected component on a grid
923
Chapter 130. Largest connected component on a grid
924
Chapter 130. Largest connected component on a grid
}
}
}
// function to print the result
static void print_result(int res)
{
System.out.println ("The largest connected " +
"component of the grid is :" +
res );
// prints the largest component
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (result[i][j] != 0)
System.out.print(result[i][j] + " ");
else
System.out.print(". ");
}
System.out.println();
}
}
// function to calculate the
// largest connected component
static void computeLargestConnectedGrid(int input[][])
{
int current_max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
reset_visited();
COUNT = 0;
// checking cell to the right
if (j + 1 < m)
BFS(input[i][j], input[i][j + 1],
i, j, input);
// updating result
if (COUNT >= current_max)
{
current_max = COUNT;
reset_result(input[i][j], input);
925
Chapter 130. Largest connected component on a grid
}
reset_visited();
COUNT = 0;
// checking cell downwards
if (i + 1 < n)
BFS(input[i][j],
input[i + 1][j], i, j, input);
// updating result
if (COUNT >= current_max)
{
current_max = COUNT;
reset_result(input[i][j], input);
}
}
}
print_result(current_max);
}
// Driver Code
public static void main(String args[])
{
int input[][] = {{1, 4, 4, 4, 4, 3, 3, 1},
{2, 1, 1, 4, 3, 3, 1, 1},
{3, 2, 1, 1, 2, 3, 2, 1},
{3, 3, 2, 1, 2, 2, 2, 2},
{3, 1, 3, 1, 1, 4, 4, 4},
{1, 1, 3, 1, 1, 4, 4, 4}};
// function to compute the largest
// connected component in the grid
computeLargestConnectedGrid(input);
}
}
// This code is contributed by Subhadeep
Output:
926
Chapter 130. Largest connected component on a grid
Improved By : tufan_gupta2000
Source
https://www.geeksforgeeks.org/largest-connected-component-on-a-grid/
927
Chapter 131
k = 5
Output : Area = 12
(Top, Left): (0, 0)
(Bottom, Right): (2, 3)
The sub-matrix is:
| 1, 2, -1, -4 |
| -8, -3, 4, 2 |
| 3, 8, 10, 1 |
Naive Approach: Check every possible rectangle in given 2D array having sum divisible
by ‘k’ and print the largest one. This solution requires 4 nested loops and time complexity
of this solution would be O(n^4).
Efficient Approach: Longest subarray having sum divisible by k for 1-D array can be
used to reduce the time complexity to O(n^3). The idea is to fix the left and right columns
one by one and find the longest sub-array having sum divisible by ‘k’ for contiguous rows
928
Chapter 131. Largest rectangular sub-matrix having sum divisible by k
for every left and right column pair. We basically find top and bottom row numbers (which
are part of the largest sub-matrix) for every fixed left and right column pair. To find the top
and bottom row numbers, calculate sum of elements in every row from left to right and store
these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right
in row i. Now, apply Longest subarray having sum divisible by k 1D algorithm on temp[],
and get the longest sub-array having sum divisible by ‘k’ of temp[]. This length would be
the maximum possible length with left and right as boundary columns. Set the ‘top’ and
‘bottom’ row indexes for the left right column pair and calculate the area. In similar manner
get the top, bottom, left, right indexes for other sub-matrices having sum divisible by ‘k’
and print the one having maximum area.
929
Chapter 131. Largest rectangular sub-matrix having sum divisible by k
930
Chapter 131. Largest rectangular sub-matrix having sum divisible by k
Output:
931
Chapter 131. Largest rectangular sub-matrix having sum divisible by k
Area: 12
Source
https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-sum-divisible-k/
932
Chapter 132
Examples:
Input : 1, 2, 3
-3, -2, -1
1, 7, 5
Output : 1, 2, 3
-3, -2, -1
933
Chapter 132. Largest rectangular sub-matrix whose sum is 0
Input : 9, 7, 16, 5
1, -6, -7, 3
1, 8, 7, 9
7, -2, 0, 10
Output :-6, -7
8, 7
-2, 0
The naive solution for this problem is to check every possible rectangle in given 2D array.
This solution requires 4 nested loops and time complexity of this solution would be O(n^4).
The solution is based onMaximum sum rectangle in a 2D matrix. The idea is to reduce
the problem to 1 D array. We can use Hashing to find maximum length of sub-array in
1-D array in O(n) time. We fix the left and right columns one by one and find the largest
sub-array with 0 sum contiguous rows for every left and right column pair. We basically
find top and bottom row numbers (which have sum is zero) for every fixed left and right
column pair. To find the top and bottom row numbers, calculate sum of elements in every
row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum
of elements from left to right in row i. If we find largest subarray with 0 sum on temp, and
no. of elements is greater than previous no. of elements then update the values of final
row_up, final row_down, final col_left, final col_right.
934
Chapter 132. Largest rectangular sub-matrix whose sum is 0
{
// Add current element to sum
sum += temp[i];
if (temp[i] == 0 && max_length == 0)
{
*starti = i;
*endj = i;
max_length = 1;
}
if (sum == 0)
{
if (max_length < i + 1)
{
*starti = 0;
*endj = i;
}
max_length = i + 1;
}
// Look for this sum in Hash table
if (presum.find(sum) != presum.end())
{
// store previous max_length so
// that we can check max_length
// is updated or not
int old = max_length;
// If this sum is seen before,
// then update max_len
max_length = max(max_length, i - presum[sum]);
if (old < max_length)
{
// If max_length is updated then
// enter and update start and end
// point of array
*endj = i;
*starti = presum[sum] + 1;
}
}
else
// Else insert this sum with
// index in hash table
presum[sum] = i;
}
935
Chapter 132. Largest rectangular sub-matrix whose sum is 0
936
Chapter 132. Largest rectangular sub-matrix whose sum is 0
fdown = down;
fleft = left;
fright = right;
maxl = ele;
}
}
}
// If there is no change in boundaries
// than check if a[0][0] is 0
// If it not zero then print
// that no such zero-sum sub-matrix exists
if (fup == 0 && fdown == 0 && fleft == 0 &&
fright == 0 && a[0][0] != 0) {
cout << "No zero-sum sub-matrix exists";
return;
}
// Print final values
for (int j = fup; j <= fdown; j++)
{
for (int i = fleft; i <= fright; i++)
cout << a[j][i] << " ";
cout << endl;
}
}
// Driver program to test above functions
int main()
{
int a[][MAX] = { { 9, 7, 16, 5 }, { 1, -6, -7, 3 },
{ 1, 8, 7, 9 }, { 7, -2, 0, 10 } };
int row = 4, col = 4;
sumZeroMatrix(a, row, col);
return 0;
}
Output:
-6, -7
8, 7
-2, 0
Source
https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-whose-sum-0/
937
Chapter 133
Input : mat[][] = 3 1 2
4 8 5
6 9 7
Output : 18
Zigzag sequence is: 3->8->7
Another such sequence is 2->4->7
Input : mat[][] = 4 2 1
3 9 6
11 3 15
Output : 28
938
Chapter 133. Largest sum Zigzag sequence in a matrix
C++
939
Chapter 133. Largest sum Zigzag sequence in a matrix
{11, 3, 15}};
cout << "Largest zigzag sum: " << largestZigZag(mat, n);
return 0;
}
Java
940
Chapter 133. Largest sum Zigzag sequence in a matrix
largestZigZagSumRec(mat, 0, j, n));
return res;
}
// Driver program to test above
public static void main (String[] args)
{
int n = 3;
int mat[][] = { {4, 2, 1},
{3, 9, 6},
{11, 3, 15} };
System.out.println( "Largest zigzag sum: "
+ largestZigZag(mat, n));
}
}
// This code is contributed by anuj_67.
C#
941
Chapter 133. Largest sum Zigzag sequence in a matrix
return zzs + mat[i,j];
}
// Returns largest possible
// sum of a Zizag sequence
// starting from top and ending
// at bottom.
static int largestZigZag(int [,]mat, int n)
{
// Consider all cells of
// top row as starting
// point
int res = 0;
for (int j = 0; j < n; j++)
res = Math.Max(res,
largestZigZagSumRec(mat, 0, j, n));
return res;
}
// Driver Code
public static void Main ()
{
int n = 3;
int [,]mat = {{4, 2, 1},
{3, 9, 6},
{11, 3, 15}};
Console.WriteLine("Largest zigzag sum: "
+ largestZigZag(mat, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find the
// largest sum zigzag sequence
$MAX = 100;
// Returns largest sum of a
// Zigzag sequence starting
// from (i, j) and ending at
// a bottom cell.
942
Chapter 133. Largest sum Zigzag sequence in a matrix
Output:
943
Chapter 133. Largest sum Zigzag sequence in a matrix
Overlapping Subproblems
Considering the above implementation, for a matrix mat[][] of size 3 x 3, to find zigzag
sum(zzs) for an element mat(i,j), the following recursion tree is formed.
We can see that there are many subproblems which are solved again and again. So this
problem has Overlapping Substructure property and recomputation of same subproblems
can be avoided by either using Memoization or Tabulation. Following is a tabluated imple-
mentation for the LIS problem.
944
Chapter 133. Largest sum Zigzag sequence in a matrix
int j, int n)
{
if (dp[i][j] != -1)
return dp[i][j];
// If we have reached bottom
if (i == n-1)
return (dp[i][j] = mat[i][j]);
// Find the largest sum by considering all
// possible next elements in sequence.
int zzs = 0;
for (int k=0; k<n; k++)
if (k != j)
zzs = max(zzs, largestZigZagSumRec(mat, i+1, k, n));
return (dp[i][j] = (zzs + mat[i][j]));
}
// Returns largest possible sum of a Zizag sequence
// starting from top and ending at bottom.
int largestZigZag(int mat[][MAX], int n)
{
memset(dp, -1, sizeof(dp));
// Consider all cells of top row as starting point
int res = 0;
for (int j=0; j<n; j++)
res = max(res, largestZigZagSumRec(mat, 0, j, n));
return res;
}
// Driver program to test above
int main()
{
int n = 3;
int mat[][MAX] = { {4, 2, 1},
{3, 9, 6},
{11, 3, 15}};
cout << "Largest zigzag sum: " << largestZigZag(mat, n);
return 0;
}
Output:
28
945
Chapter 133. Largest sum Zigzag sequence in a matrix
Source
https://www.geeksforgeeks.org/largest-sum-zig-zag-sequence-in-a-matrix/
946
Chapter 134
Latin Square
Input: 3
Output: 1 2 3
3 1 2
2 3 1
Input: 5
Output: 1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
Did you find any pattern in which the number are stored in a Latin Square?
Note: There may be more than one possible configuration of a n x n latin square.
C++
947
Chapter 134. Latin Square
Java
948
Chapter 134. Latin Square
C#
949
Chapter 134. Latin Square
950
Chapter 134. Latin Square
}
// This code is contributed by KRV.
PHP
<?php
// PHP program to print Latin Square
// Function to print n x n Latin Square
function printLatin( $n)
{
// A variable to control
// the rotation point.
$k = $n + 1;
// Loop to print rows
for ( $i = 1; $i <= $n; $i++)
{
// This loops runs only after
// first iteration of outer loop.
// It prints numbers from n to k
$temp = $k;
while ($temp <= $n)
{
echo $temp," ";
$temp++;
}
// This loop prints numbers
// from 1 to k-1.
for ($j = 1; $j < $k; $j++)
echo $j, " ";
$k--;
echo "\n";
}
}
// Driver Code
$n = 5;
// Invoking printLatin function
printLatin($n);
// This code is contributed by anuj_67.
?>
951
Chapter 134. Latin Square
Output :
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
Reference:
https://en.wikipedia.org/wiki/Latin_square
Improved By : KRV, vt_m
Source
https://www.geeksforgeeks.org/latin-square/
952
Chapter 135
Input : N = 4, M = 4
m[][] = { { 1, 2, 3, 4 },
{ 2, 2, 3, 4 },
{ 3, 2, 3, 4 },
{ 4, 5, 6, 7 } };
Output : 7
Longest path is 1 2 3 4 5 6 7.
Input : N = 2, M =2
m[][] = { { 1, 2 },
{ 3, 4 } };
Output :3
Longest path is either 1 2 4 or
1 3 4.
The idea is to use dynamic programming. Maintain the 2D matrix, dp[][], where dp[i][j]
store the value of length of longest increasing sequence for sub matrix starting from ith row
and j-th column.
Let the longest increasing sub sequence values for m[i+1][j] and m[i][j+1] be known already
as v1 and v2 respectively. Then the value for m[i][j] will be max(v1, v2) + 1.
We can start from m[n-1][m-1] as base case with length of longest increasing sub sequence
953
Chapter 135. Longest Increasing Path in Matrix
be 1, moving upwards and leftwards updating the value of cells. Then the LIP value for cell
m[0][0] will be the answer.
Below is the implementation of this approach:
C++
954
Chapter 135. Longest Increasing Path in Matrix
return LIP(dp, mat, n, m, 0, 0);
}
// Driven Program
int main()
{
int mat[][MAX] = {
{ 1, 2, 3, 4 },
{ 2, 2, 3, 4 },
{ 3, 2, 3, 4 },
{ 4, 5, 6, 7 },
};
int n = 4, m = 4;
cout << wrapper(mat, n, m) << endl;
return 0;
}
Java
955
Chapter 135. Longest Increasing Path in Matrix
Output:
Source
https://www.geeksforgeeks.org/longest-increasing-path-matrix/
956
Chapter 136
The idea is to use Backtracking. We start from the source cell of the matrix, move forward
in all four allowed directions and recursively checks if they leads to the solution or not. If
destination is found, we update the value of longest path else if none of the above solutions
work we return false from our function.
Below is C++ implementation of above idea –
957
Chapter 136. Longest Possible Route in a Matrix with Hurdles
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 10
// A Pair to store status of a cell. found is set to
// true of destination is reachable and value stores
// distance of longest path
struct Pair
{
// true if destination is found
bool found;
// stores cost of longest path from current cell to
// destination cell
int value;
};
// Function to find Longest Possible Route in the
// matrix with hurdles. If the destination is not reachable
// the function returns false with cost INT_MAX.
// (i, j) is source cell and (x, y) is destination cell.
Pair findLongestPathUtil(int mat[R][C], int i, int j,
int x, int y, bool visited[R][C])
{
// if (i, j) itself is destination, return true
if (i == x && j == y)
{
Pair p = { true, 0 };
return p;
}
// if not a valid cell, return false
if (i < 0 || i >= R || j < 0 || j >= C ||
mat[i][j] == 0 || visited[i][j])
{
Pair p = { false, INT_MAX };
return p;
}
// include (i, j) in current path i.e.
// set visited(i, j) to true
visited[i][j] = true;
// res stores longest path from current cell (i, j) to
// destination cell (x, y)
int res = INT_MIN;
958
Chapter 136. Longest Possible Route in a Matrix with Hurdles
// go left from current cell
Pair sol = findLongestPathUtil(mat, i, j - 1, x, y, visited);
// if destination can be reached on going left from current
// cell, update res
if (sol.found)
res = max(res, sol.value);
// go right from current cell
sol = findLongestPathUtil(mat, i, j + 1, x, y, visited);
// if destination can be reached on going right from current
// cell, update res
if (sol.found)
res = max(res, sol.value);
// go up from current cell
sol = findLongestPathUtil(mat, i - 1, j, x, y, visited);
// if destination can be reached on going up from current
// cell, update res
if (sol.found)
res = max(res, sol.value);
// go down from current cell
sol = findLongestPathUtil(mat, i + 1, j, x, y, visited);
// if destination can be reached on going down from current
// cell, update res
if (sol.found)
res = max(res, sol.value);
// Backtrack
visited[i][j] = false;
// if destination can be reached from current cell,
// return true
if (res != INT_MIN)
{
Pair p = { true, 1 + res };
return p;
}
// if destination can't be reached from current cell,
// return false
else
{
959
Chapter 136. Longest Possible Route in a Matrix with Hurdles
Output:
960
Chapter 136. Longest Possible Route in a Matrix with Hurdles
Source
https://www.geeksforgeeks.org/longest-possible-route-in-a-matrix-with-hurdles/
961
Chapter 137
Magic Square
In this post, we will discuss how programmatically we can generate a magic square of size
n. Before we go further, consider the below examples:
962
Chapter 137. Magic Square
11 10 4 23 17
Sum in each row & each column = 5*(5^2+1)/2 = 65
Did you find any pattern in which the numbers are stored?
In any magic square, the first number i.e. 1 is stored at position (n/2, n-1). Let this position
be (i,j). The next number is stored at position (i-1, j+1) where we can consider each row &
column as circular array i.e. they wrap around.
Three conditions hold:
1. The position of next number is calculated by decrementing row number of previous
number by 1, and incrementing the column number of previous number by 1. At any time,
if the calculated row position becomes -1, it will wrap around to n-1. Similarly, if the
calculated column position becomes n, it will wrap around to 0.
2. If the magic square already contains a number at the calculated position, calculated
column position will be decremented by 2, and calculated row position will be incremented
by 1.
3. If the calculated row position is -1 & calculated column position is n, the new position
would be: (0, n-2).
Example:
Magic Square of size 3
----------------------
2 7 6
9 5 1
4 3 8
Steps:
1. position of number 1 = (3/2, 3-1) = (1, 2)
2. position of number 2 = (1-1, 2+1) = (0, 0)
3. position of number 3 = (0-1, 0+1) = (3-1, 1) = (2, 1)
4. position of number 4 = (2-1, 1+1) = (1, 2)
Since, at this position, 1 is there. So, apply condition 2.
new position=(1+1,2-2)=(2,0)
5. position of number 5=(2-1,0+1)=(1,1)
963
Chapter 137. Magic Square
C/C++
964
Chapter 137. Magic Square
{
j -= 2;
i++;
continue;
}
else
magicSquare[i][j] = num++; //set number
j++; i--; //1st condition
}
// Print magic square
printf("The Magic Square for n=%d:\nSum of "
"each row or column %d:\n\n", n, n*(n*n+1)/2);
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
printf("%3d ", magicSquare[i][j]);
printf("\n");
}
}
// Driver program to test above function
int main()
{
int n = 7; // Works only when n is odd
generateSquare (n);
return 0;
}
Java
965
Chapter 137. Magic Square
{
if (i==-1 && j==n) //3rd condition
{
j = n-2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
//1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i=n-1;
}
//2nd condition
if (magicSquare[i][j] != 0)
{
j -= 2;
i++;
continue;
}
else
//set number
magicSquare[i][j] = num++;
//1st condition
j++; i--;
}
// print magic square
System.out.println("The Magic Square for "+n+":");
System.out.println("Sum of each row or column "+n*(n*n+1)/2+":");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
System.out.print(magicSquare[i][j]+" ");
System.out.println();
}
}
// driver program
public static void main (String[] args)
{
966
Chapter 137. Magic Square
Python
967
Chapter 137. Magic Square
continue
else:
magicSquare[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1 # 1st condition
# Printing magic square
print ("Magic Squre for n =", n)
print ("Sum of each row or column",
n * (n * n + 1) / 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (magicSquare[i][j]),
end = '')
# To display output
# in matrix form
if j == n - 1:
print()
# Driver Code
# Works only when n is odd
n = 7
generateSquare(n)
# This code is contributed
# by Harshit Agrawal
C#
968
Chapter 137. Magic Square
// One by one put all values in magic square
for (int num = 1; num <= n * n; )
{
if (i == -1 && j == n) //3rd condition
{
j = n - 2;
i = 0;
}
else
{
//1st condition helper if next number
// goes to out of square's right side
if (j == n)
j = 0;
//1st condition helper if next number is
// goes to out of square's upper side
if (i < 0)
i = n - 1;
}
//2nd condition
if (magicSquare[i, j] != 0)
{
j -= 2;
i++;
continue;
}
else
//set number
magicSquare[i, j] = num++;
//1st condition
j++; i--;
}
// print magic square
Console.WriteLine("The Magic Square for "
+ n + ":");
Console.WriteLine("Sum of each row or column "
+ n * (n * n + 1) / 2 + ":");
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
Console.Write(magicSquare[i, j] + " ");
Console.WriteLine();
969
Chapter 137. Magic Square
}
}
// driver program
public static void Main ()
{
// Works only when n is odd
int n = 7;
generateSquare(n);
}
}
// This code is contributed by Sam007.
PHP
<?php
// php program to generate odd sized
// magic squares
// A function to generate odd sized
// magic squares
function generateSquare($n)
{
// set all slots as 0
$magicSquare;
for ($i = 0; $i < $n; $i++)
for ($j = 0; $j < $n; $j++)
$magicSquare[$i][$j] = 0;
// Initialize position for 1
$i = (int)$n / 2;
$j = $n - 1;
// One by one put all values in
// magic square
for ($num = 1; $num <= $n * $n; )
{
// 3rd condition
if ($i == -1 && $j == $n)
{
$j = $n-2;
$i = 0;
}
970
Chapter 137. Magic Square
else
{
// 1st condition helper if
// next number goes to out
// of square's right side
if ($j == $n)
$j = 0;
// 1st condition helper if
// next number is goes to
// out of square's upper
// side
if ($i < 0)
$i = $n-1;
}
// 2nd condition
if ($magicSquare[$i][$j])
{
$j -= 2;
$i++;
continue;
}
else
// set number
$magicSquare[$i][$j] = $num++;
// 1st condition
$j++; $i--;
}
// Print magic square
echo "The Magic Square for n = " . $n
. ":\nSum of each row or column "
. $n * ($n * $n + 1) / 2;
echo "\n\n";
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
echo $magicSquare[$i][$j] . " ";
echo "\n";
}
}
// Driver program to test above function
971
Chapter 137. Magic Square
Output:
20 12 4 45 37 29 28
11 3 44 36 35 27 19
2 43 42 34 26 18 10
49 41 33 25 17 9 1
40 32 24 16 8 7 48
31 23 15 14 6 47 39
22 21 13 5 46 38 30
Source
https://www.geeksforgeeks.org/magic-square/
972
Chapter 138
973
Chapter 138. Magic Square | Even Order
33 34 30 29 28 27 39 40
41 42 22 21 20 19 47 48
16 15 51 52 53 54 10 9
8 7 59 60 61 62 2 1
A bit of Theory:
Magic squares are divided into three major categories depending upon order of square.
1) Odd order Magic Square. Example: 3,5,7,… (2*n +1)
2) Doubly-even order Magic Square. Example : 4,8,12,16,.. (4*n)
3) Singly-even order Magic Square. Example : 6,10,14,18,..(4*n +2)
Algorithm for Doubly-even Magic Square :
974
Chapter 138. Magic Square | Even Order
{
for ( j = 0; j<n/4; j++)
arr[i][j] = (n*n + 1) - arr[i][j];
}
975
Chapter 138. Magic Square | Even Order
C/C++
976
Chapter 138. Magic Square | Even Order
977
Chapter 138. Magic Square | Even Order
Java
978
Chapter 138. Magic Square | Even Order
Python
979
Chapter 138. Magic Square | Even Order
# Change value of array elements at fix location
# as per the rule (n*n+1)-arr[i][[j]
# Corners of order (n/4)*(n/4)
# Top left corner
for i in range(0,n/4):
for j in range(0,n/4):
arr[i][j] = (n*n + 1) - arr[i][j];
# Top right corner
for i in range(0,n/4):
for j in range(3 * (n/4),n):
arr[i][j] = (n*n + 1) - arr[i][j];
# Bottom Left corner
for i in range(3 * (n/4),n):
for j in range(0,n/4):
arr[i][j] = (n*n + 1) - arr[i][j];
# Bottom Right corner
for i in range(3 * (n/4),n):
for j in range(3 * (n/4),n):
arr[i][j] = (n*n + 1) - arr[i][j];
# Centre of matrix,order (n/2)*(n/2)
for i in range(n/4,3 * (n/4)):
for j in range(n/4,3 * (n/4)):
arr[i][j] = (n*n + 1) - arr[i][j];
# Printing the square
for i in range(n):
for j in range(n):
print '%2d ' %(arr[i][j]),
print
# Driver Program
n = 8
DoublyEven(n)
# Contributed by Harshit Agrawal
Output:
64 63 3 4 5 6 58 57
56 55 11 12 13 14 50 49
17 18 46 45 44 43 23 24
980
Chapter 138. Magic Square | Even Order
25 26 38 37 36 35 31 32
33 34 30 29 28 27 39 40
41 42 22 21 20 19 47 48
16 15 51 52 53 54 10 9
8 7 59 60 61 62 2 1
Source
https://www.geeksforgeeks.org/magic-square-even-order/
981
Chapter 139
However, the order in which we parenthesize the product affects the number of simple arith-
metic operations needed to compute the product, or the efficiency. For example, suppose A
is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,
982
Chapter 139. Matrix Chain Multiplication | DP-8
1) Optimal Substructure:
A simple solution is to place parenthesis at all possible places, calculate the cost for each
placement and return the minimum value. In a chain of matrices of size n, we can place
the first set of parenthesis in n-1 ways. For example, if the given chain is of 4 matrices.
let the chain be ABCD, then there are 3 ways to place first set of parenthesis outer side:
(A)(BCD), (AB)(CD) and (ABC)(D). So when we place a set of parenthesis, we divide the
problem into subproblems of smaller size. Therefore, the problem has optimal substructure
property and can be easily solved using recursion.
Minimum number of multiplication needed to multiply a chain of size n = Minimum of all
n-1 placements (these placements create subproblems of smaller size)
2) Overlapping Subproblems
Following is a recursive implementation that simply follows the above optimal substructure
property.
983
Chapter 139. Matrix Chain Multiplication | DP-8
Java
984
Chapter 139. Matrix Chain Multiplication | DP-8
Python3
985
Chapter 139. Matrix Chain Multiplication | DP-8
C#
986
Chapter 139. Matrix Chain Multiplication | DP-8
Time complexity of the above naive recursive approach is exponential. It should be noted
that the above function computes the same subproblems again and again. See the following
recursion tree for a matrix chain of size 4. The function MatrixChainOrder(p, 3, 4) is called
two times. We can see that there are many subproblems being called more than once.
987
Chapter 139. Matrix Chain Multiplication | DP-8
Since same suproblems are called again, this problem has Overlapping Subprolems property.
So Matrix Chain Multiplication problem has both properties (see thisand this) of a dynamic
programming problem. Like other typical Dynamic Programming(DP) problems, recompu-
tations of same subproblems can be avoided by constructing a temporary array m[][] in
bottom up manner.
Dynamic Programming Solution
Following is C/C++ implementation for Matrix Chain Multiplication problem using
Dynamic Programming.
988
Chapter 139. Matrix Chain Multiplication | DP-8
}
}
}
return m[1][n-1];
}
int main()
{
int arr[] = {1, 2, 3, 4};
int size = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ",
MatrixChainOrder(arr, size));
getchar();
return 0;
}
Java
989
Chapter 139. Matrix Chain Multiplication | DP-8
{
j = i+L-1;
if(j == n) continue;
m[i][j] = Integer.MAX_VALUE;
for (k=i; k<=j-1; k++)
{
// q = cost/scalar multiplications
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
m[i][j] = q;
}
}
}
return m[1][n-1];
}
// Driver program to test above function
public static void main(String args[])
{
int arr[] = new int[] {1, 2, 3, 4};
int size = arr.length;
System.out.println("Minimum number of multiplications is "+
MatrixChainOrder(arr, size));
}
}
/* This code is contributed by Rajat Mishra*/
Python
990
Chapter 139. Matrix Chain Multiplication | DP-8
C#
991
Chapter 139. Matrix Chain Multiplication | DP-8
/* m[i,j] = Minimum number of scalar
multiplications needed
to compute the matrix A[i]A[i+1]...A[j]
= A[i..j] where dimension of A[i] is
p[i-1] x p[i] */
// cost is zero when multiplying
// one matrix.
for (i = 1; i < n; i++)
m[i, i] = 0;
// L is chain length.
for (L = 2; L < n; L++)
{
for (i = 1; i < n-L+1; i++)
{
j = i+L-1;
if(j == n) continue;
m[i, j] = int.MaxValue;
for (k = i; k <= j-1; k++)
{
// q = cost/scalar multiplications
q = m[i, k] + m[k+1, j] +
p[i-1]*p[k]*p[j];
if (q < m[i, j])
m[i, j] = q;
}
}
}
return m[1, n-1];
}
// Driver program to test above function
public static void Main()
{
int []arr = new int[] {1, 2, 3, 4};
int size = arr.Length;
Console.Write("Minimum number of " +
"multiplications is "+
MatrixChainOrder(arr, size));
}
}
// This code is contributed by Sam007
992
Chapter 139. Matrix Chain Multiplication | DP-8
Output:
Source
https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/
993
Chapter 140
Matrix Exponentiation
994
Chapter 140. Matrix Exponentiation
C = [a b c
1 0 0
0 1 0]
- - - - 2 times - - -
| F(4) | = | a b c | * | a b c | * | F(2) |
| F(3) | | 1 0 0 | | 1 0 0 | | F(1) |
| F(2) | | 0 1 0 | | 0 1 0 | | F(0) |
- - - - - - - - n -2 times - - - - -
| F(n) | = | a b c | * | a b c | * ... * | a b c | * | F(2) |
| F(n-1) | | 1 0 0 | | 1 0 0 | | 1 0 0 | | F(1) |
| F(n-2) | | 0 1 0 | | 0 1 0 | | 0 1 0 | | F(0) |
995
Chapter 140. Matrix Exponentiation
| F(n-2) | [ | 0 1 0 | ] | F(0) |
So we can simply multiply our Second matrix n-2 times and then multiply it with the
third matrix to get the result. Multiplication can be done in (log n) time using Divide and
Conquer algorithm for power (See this or this)
Let us consider the problem of finding n’th term of a series defined using below recurrence.
n'th term,
F(n) = F(n-1) + F(n-2) + F(n-3), n >= 3
Base Cases :
F(0) = 0, F(1) = 1, F(2) = 1
996
Chapter 140. Matrix Exponentiation
mul[i][j] += a[i][k]*b[k][j];
}
}
// storing the muliplication resul in a[][]
for (int i=0; i<3; i++)
for (int j=0; j<3; j++)
a[i][j] = mul[i][j]; // Updating our matrix
}
// Function to compute F raise to power n-2.
int power(int F[3][3], int n)
{
int M[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}};
// Multiply it with initial values i.e with
// F(0) = 0, F(1) = 1, F(2) = 1
if (n==1)
return F[0][0] + F[0][1];
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
// Multiply it with initial values i.e with
// F(0) = 0, F(1) = 1, F(2) = 1
return F[0][0] + F[0][1] ;
}
// Return n'th term of a series defined using below
// recurrence relation.
// f(n) is defined as
// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3
// Base Cases :
// f(0) = 0, f(1) = 1, f(2) = 1
int findNthTerm(int n)
{
int F[3][3] = {{1,1,1}, {1,0,0}, {0,1,0}} ;
return power(F, n-2);
}
// Driver code
int main()
{
997
Chapter 140. Matrix Exponentiation
int n = 5;
cout << "F(5) is " << findNthTerm(n);
return 0;
}
Java
998
Chapter 140. Matrix Exponentiation
999
Chapter 140. Matrix Exponentiation
}
//This code is contributed by vt_m.
C#
1000
Chapter 140. Matrix Exponentiation
// Multiply it with initial values i.e
// with F(0) = 0, F(1) = 1, F(2) = 1
if (n == 1)
return F[0, 0] + F[0, 1];
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
// Multiply it with initial values i.e
// with F(0) = 0, F(1) = 1, F(2) = 1
return F[0, 0] + F[0, 1];
}
// Return n'th term of a series defined
// using below recurrence relation.
// f(n) is defined as
// f(n) = f(n-1) + f(n-2) + f(n-3), n>=3
// Base Cases :
// f(0) = 0, f(1) = 1, f(2) = 1
static int findNthTerm(int n)
{
int[, ] F = { { 1, 1, 1 }, { 1, 0, 0 },
{ 0, 1, 0 } };
return power(F, n - 2);
}
// Driver code
public static void Main()
{
int n = 5;
Console.WriteLine("F(5) is "
+ findNthTerm(n));
}
}
// This code is contributed by vt_m.
Output :
F(5) is 7
1001
Chapter 140. Matrix Exponentiation
Source
https://www.geeksforgeeks.org/matrix-exponentiation/
1002
Chapter 141
Matrix Multiplication |
Recursive
Input: A = 12 56
45 78
B = 2 6
5 8
Output: 304 520
480 894
Input: A = 1 2 3
4 5 6
7 8 9
B = 1 2 3
4 5 6
7 8 9
Output: 30 36 42
66 81 96
102 126 150
1003
Chapter 141. Matrix Multiplication | Recursive
of columns of first matrix is equal to number of rows of second matrix or not. If both are
equal than proceed further otherwise generate output “Not Possible”.
In Recursive Matrix Multiplication, we implement three loops of Iteration through recursive
calls. The inner most Recursive call of multiplyMatrix() is to iterate k (col1 or row2).
The second recursive call of multiplyMatrix() is to change the columns and the outermost
recursive call is to change rows.
Below is Recursive Matrix Multiplication code.
C/C++
1004
Chapter 141. Matrix Multiplication | Recursive
j = 0;
i++;
multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
}
// Function to multiply two matrices A[][] and B[][]
void multiplyMatrix(int row1, int col1, int A[][MAX],
int row2, int col2, int B[][MAX])
{
if (row2 != col1)
{
printf("Not Possible\n");
return;
}
int C[MAX][MAX] = {0};
multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
// Print the result
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col2; j++)
printf("%d ", C[i][j]);
printf("\n");
}
}
// Driven Program
int main()
{
int A[][MAX] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int B[][MAX] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
int row1 = 3, col1 = 3, row2 = 3, col2 = 3;
multiplyMatrix(row1, col1, A, row2, col2, B);
return 0;
}
Java
1005
Chapter 141. Matrix Multiplication | Recursive
1006
Chapter 141. Matrix Multiplication | Recursive
System.out.println("Not Possible\n");
return;
}
int[][] C = new int[MAX][MAX];
multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
// Print the result
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col2; j++)
System.out.print(C[i][j]+" ");
System.out.println();
}
}
// driver program
public static void main (String[] args)
{
int row1 = 3, col1 = 3, row2 = 3, col2 = 3;
int A[][] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int B[][] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
multiplyMatrix(row1, col1, A, row2, col2, B);
}
}
// Contributed by Pramod Kumar
C#
1007
Chapter 141. Matrix Multiplication | Recursive
1008
Chapter 141. Matrix Multiplication | Recursive
Console.WriteLine("Not Possible\n");
return;
}
int[,]C = new int[MAX, MAX];
multiplyMatrixRec(row1, col1, A,
row2, col2, B, C);
// Print the result
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col2; j++)
Console.Write(C[i, j] + " ");
Console.WriteLine();
}
}
// Driver Code
static public void Main ()
{
int row1 = 3, col1 = 3,
row2 = 3, col2 = 3;
int [,]A = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int [,]B = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
multiplyMatrix(row1, col1, A,
row2, col2, B);
}
}
// This code is contributed by m_kit
Output :
30 36 42
66 81 96
102 126 150
Improved By : jit_t
1009
Chapter 141. Matrix Multiplication | Recursive
Source
https://www.geeksforgeeks.org/matrix-multiplication-recursive/
1010
Chapter 142
1011
Chapter 142. Matrix manipulation in Python
Output :
Output :
6. sqrt() :- This function is used to compute the square root of each element of matrix.
1012
Chapter 142. Matrix manipulation in Python
7. sum(x,axis) :- This function is used to add all the elements in matrix. Optional
“axis” argument computes the column sum if axis is 0 and row sum if axis is 1.
8. “T” :- This argument is used to transpose the specified matrix.
Output :
1013
Chapter 142. Matrix manipulation in Python
[[1 4]
[2 5]]
Source
https://www.geeksforgeeks.org/matrix-manipulation-python/
1014
Chapter 143
A simple solution is to traverse through matrix. For every visited cell, check if it is the
cell to be ignored.
C++
1015
Chapter 143. Matrix sum except one item
Java
1016
Chapter 143. Matrix sum except one item
C#
1017
Chapter 143. Matrix sum except one item
Python 3
PHP
<?php
// PHP program to find
// sum of matrix except
// cell (x, y)
$R = 2;
$C = 3;
// Returns sum of arr[][]
// except cell arr[x][y]
function calcSum(&$arr, $x, $y)
{
global $R,$C;
$sum = 0;
for ($i = 0; $i < $R; $i++)
1018
Chapter 143. Matrix sum except one item
{
for ($j = 0; $j < $C; $j++)
{
if ($i != $x || $j != $y)
$sum = $sum + $arr[$i][$j];
}
}
return $sum;
}
// Driver code
$x = 0;
$y = 2;
$arr = array(array(1, 2, 4),
array(5, 6, 8));
echo (calcSum($arr, $x, $y));
// This code is contributed
// by ChitraNayal
?>
Output:
22
The above solution causes an extra comparison for every matrix item. A better solution
is to first find overall sum, then subtract given cell.
C++
1019
Chapter 143. Matrix sum except one item
Java
C#
1020
Chapter 143. Matrix sum except one item
Python 3
1021
Chapter 143. Matrix sum except one item
# Driver code
x = 0
y = 2
R = 2
C = 3
arr = [[1, 2, 4 ],
[5, 6, 8 ]]
print (calcSum(arr, x, y))
# This code is contributed
# by ChitraNayal
PHP
<?php
// PHP program to find sum
// of matrix except cell (x, y)
$R = 2;
$C = 3;
// Returns sum of $arr[][]
// except cell $arr[$x][$y]
function calcSum(&$arr, $x, $y)
{
global $R,$C;
$sum = 0;
for ($i = 0; $i < $R; $i++)
for ($j = 0; $j < $C; $j++)
$sum = $sum + $arr[$i][$j];
return $sum - $arr[$x][$y];
}
// Driver code
$x = 0;
$y = 2;
$arr= array(array(1, 2, 4 ),
array(5, 6, 8 ));
echo (calcSum($arr, $x, $y));
// This code is contributed
// by ChitraNayal
?>
Output:
1022
Chapter 143. Matrix sum except one item
22
Improved By : ChitraNayal
Source
https://www.geeksforgeeks.org/matrix-sum-except-one-item/
1023
Chapter 144
Note: The elements should remain within the range 0 to M after applying above operations.
The task is to find the maximum value of the expression shown below that can be obtained
after performing the above operation on matrix if required:
res += (i+j)*A[i][j]
Examples:
1024
Chapter 144. Maximize matrix as per given condition
5, 4}
M = 6
Output : RESULT = 43
Matrix : 0 4
6 6
Algorithm :
Below is the step by step algorithm to do this:
1. First of all, calculate the sum of all elements of given matrix as SUM.
2. Start from last element that i.e. A(n, n) and move backward towards A(0,0) anti-
diagonally as A(n, n), A(n, n-1), A(n-1, n), A(n, n-2), A(n-1, n-1), A(n-2, n)…..
3. Fill up each cell of matrix with M and update SUM = SUM- M for each element till
SUM < M. Now, Fill the SUM value at next place in order if it is greater than zero
and all other remaining place as zero.
4. Finally you can calculate RESULT as per above mentioned formula.
Example :
Input Matrix:
1025
Chapter 144. Maximize matrix as per given condition
C++
1026
Chapter 144. Maximize matrix as per given condition
A[n-1-i][j+i] = M;
sum -= M;
}
else
{
A[n-1-i][j+i] = sum;
sum -= sum;
}
}
}
// diagonals above longest diagonal
for (int i=n-1; i>=0; i--)
{
for (int j=0; j<=i; j++)
{
if (sum > M)
{
A[i-j][j] = M;
sum -= M;
}
else
{
A[i-j][j] = sum;
sum -= sum;
}
}
}
// calculating result
for (int i=0; i<n; i++)
{
for (int j=0; j<n;j++)
res += (i+j+2) * A[i][j];
}
return res;
}
// driver program
int main()
{
int A[n][n] = { 1, 2, 3, 4,
5, 6, 7, 8,
9, 1, 1, 2,
3, 4, 5, 6};
int m = 9;
cout << maxMatrix(A, m);
return 0;
1027
Chapter 144. Maximize matrix as per given condition
}
PHP
<?php
// PHP to maximize matrix result
$n = 4;
// function for maximize
// matrix result
function maxMatrix($A, $M)
{
global $n;
$sum = 0; $res = 0;
for ($i = 0; $i < $n ; $i++)
for ($j = 0; $j < $n; $j++)
$sum += $A[$i][$j];
// diagonals below longest diagonal
// starting from last element of matrix
for ($j = $n - 1; $j > 0; $j--)
{
for ($i = 0; $i < $n - $j; $i++)
{
if ($sum > $M)
{
$A[$n - 1 - $i][$j + $i] = $M;
$sum -= $M;
}
else
{
$A[$n - 1 - $i][$j + i] = $sum;
$sum -= $sum;
}
}
}
// diagonals above longest diagonal
for ($i = $n - 1; $i >= 0; $i--)
{
for ($j = 0; $j <= $i; $j++)
{
if ($sum > $M)
{
$A[$i - $j][$j] = $M;
$sum -= $M;
}
1028
Chapter 144. Maximize matrix as per given condition
else
{
$A[$i - $j][$j] = $sum;
$sum -= $sum;
}
}
}
// calculating result
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
$res += ($i + $j + 2) *
$A[$i][$j];
}
return $res;
}
// Driver Code
$A = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 1, 1, 2),
array(3, 4, 5, 6));
$m = 9;
echo maxMatrix($A, $m);
// This code is contributed by anuj_67.
?>
Output:
425
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximize-matrix-per-given-condition/
1029
Chapter 145
Input : mat[][] = {
112, 42, 83, 119,
56, 125, 56, 49,
15, 78, 101, 43,
62, 98, 114, 108
}
Output : 414
Given matrix is of size 4 X 4, we need to maximize
the sum of upper left 2 X 2 matrix i.e
the sum of mat[0][0] + mat[0][1] + mat[1][0] + mat[1][1].
Following operations maximize the sum:
1. Reverse the column 2,
112, 42, 114, 119,
56, 125, 101, 49,
15, 78, 56, 43,
62, 98, 83, 108
2. Reverse row 0,
1030
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
To maximize the sum of upper-left submatrix, observe, for each cell of the top-left submatrix,
there are four candidates, meaning the corresponding cells in the top-left, top-right, bottom-
left, and bottom-right submatrices that it can be swapped with.
Now, observe for each cell, wherever it is, we can swap it with the corresponding candidate
value in the top-left submatrix without changing the order of the other cells in the top-left
submatrix.The diagram show for an instance where the maximum value of the 4 candidates
is in the top-right submatrix. If its is in the bottom-left or bottom-right submatrices, we
can first reverse a row or column to put it in the top-right submatrix and then follow the
same sequence of operations as shown in diagram.
In this matrix, let say a26 is the maximum of the 4 candidates and a23 must be swapped
with a26 without changing the order of the cells in the top-left submatrix.
1031
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
Reverse Row 2,
1032
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
Reverse Column 2,
1033
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
Reverse Row 7,
1034
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
Reverse Column 6,
1035
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
Reverse Row 2,
1036
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
1037
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
Output:
414
Source
https://www.geeksforgeeks.org/maximize-sum-n-x-n-upper-left-sub-matrix-given-2n-x-2n-matrix/
1038
Chapter 146
Input : R = 3, C =3
mat[][] = { 0, 0, 1,
0, 0, 1,
1, 0, 1 }
Output : 8
Flip
0 0 1
0 0 1
1 0 1
to get
1 1 1
1 1 1
0 1 1
Input : R = 2, C = 3
mat[][] = { 0, 0, 0,
0, 0, 0 }
Output : 6
1039
Chapter 146. Maximize the binary matrix by filpping submatrix once
Create a matrix ones[][] of R rows and C columns, which precomputes the number of ones
in the submatrix from (0, 0) to (i, j) by
Since, we are allowed to flip sub matrix only once. We iterate over all possible submatrices
of all possible sizes for each cell (i, j) to (i + k – 1, i + k – 1). We calculate the total number
of ones after the digits are filliped in the chosen submatrix.
Total number of ones in the final matrix after flipping submatrix (i, j) to (i + k – 1) will
be Ones in the whole matrix – Ones in the chosen submatrix + Zeroes in the chosen sub
matrix. That comes out to be :-
ones[R][C] – cal(i, j, i + k, j + k – 1) + k*k – cal(i, j, i + k – 1, j + k – 1)
where cal(a, b, c, d) denotes the number of ones in square submatrix of length c – a.
Now cal(x1, y1, x2, y2) can be define by:
ones[x2][y2] – ones[x2][y1 – 1] – ones[x1 – 1][y2] + ones[x1 – 1][y1 – 1].
Below is the C++ implementation of this approach:
1040
Chapter 146. Maximize the binary matrix by filpping submatrix once
ones[i - 1][j - 1] +
(mat[i - 1][j - 1] == 1);
// Finding the maximum number of 1s after flipping
for (int k = 1; k <= min(R, C); k++)
for (int i = 1; i + k - 1 <= R; i++)
for (int j = 1; j + k - 1 <= C; j++)
ans = max(ans, (ones[R][C] + k * k -
2 * cal(ones, i, j, k)));
return ans;
}
// Driver code
int main()
{
int mat[R][C] = {{0, 0, 1},
{ 0, 0, 1},
{ 1, 0, 1 }
};
cout << sol(mat) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximize-binary-matrix-filpping-submatrix/
1041
Chapter 147
Input : N = 3
mat[3][3] = {{1, 0, 4},
{3, 7, 2},
{5, 9, 10} };
Output : 14
We get this maximum XOR value by doing XOR
of elements in second column 0 ^ 7 ^ 9 = 14
Input : N = 4
mat[4][4] = { {1, 2, 3, 6},
{4, 5, 6,7},
{7, 8, 9, 10},
{2, 4, 5, 11}}
Output : 12
A simple solution of this problem is we can traverse the matrix twice and calculate maxi-
mum xor value row wise & column wise ,and at last return the maximum between (xor_row
, xor_column).
A efficient solution is we can traverse matrix only one time and calculate max XOR value
.
1. Start traverse the matrix and calculate XOR at each index row and column wise. We
can compute both values by using indexes in reverse way. This is possible because
matrix is a square matrix.
1042
Chapter 147. Maximum XOR value in matrix
C++
1043
Chapter 147. Maximum XOR value in matrix
{
int N = 3;
int mat[][MAX] = {{1 , 5, 4},
{3 , 7, 2 },
{5 , 9, 10}
};
cout << "maximum XOR value : "
<< maxXOR(mat, N);
return 0;
}
Java
1044
Chapter 147. Maximum XOR value in matrix
Python3
# Python3 program to Find maximum
# XOR value in matrix either row / column wise
# maximum number of row and column
MAX = 1000
# Function return the maximum
# xor value that is either row
# or column wise
def maxXOR(mat, N):
# For row xor and column xor
max_xor = 0
# Traverse matrix
for i in range(N):
r_xor = 0
c_xor = 0
for j in range(N):
1045
Chapter 147. Maximum XOR value in matrix
# xor row element
r_xor = r_xor ^ mat[i][j]
# for each column : j is act as row & i
# act as column xor column element
c_xor = c_xor ^ mat[j][i]
# update maximum between r_xor , c_xor
if (max_xor < max(r_xor, c_xor)):
max_xor = max(r_xor, c_xor)
# return maximum xor value
return max_xor
# Driver Code
N = 3
mat= [[1 , 5, 4],
[3 , 7, 2 ],
[5 , 9, 10]]
print("maximum XOR value : ",
maxXOR(mat, N))
# This code is contributed by Anant Agarwal.
C#
1046
Chapter 147. Maximum XOR value in matrix
// traverse matrix
for (int i = 0 ; i < N ; i++)
{
r_xor = 0; c_xor = 0;
for (int j = 0 ; j < N ; j++)
{
// xor row element
r_xor = r_xor^mat[i, j];
// for each column : j is act as row & i
// act as column xor column element
c_xor = c_xor^mat[j, i];
}
// update maximum between r_xor , c_xor
if (max_xor < Math.Max(r_xor, c_xor))
max_xor = Math.Max(r_xor, c_xor);
}
// return maximum xor value
return max_xor;
}
// Driver code
public static void Main ()
{
int N = 3;
int [,]mat = { {1, 5, 4},
{3, 7, 2},
{5, 9, 10}};
Console.Write("maximum XOR value : "
+ maxXOR(mat, N));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to Find
// maximum XOR value in
1047
Chapter 147. Maximum XOR value in matrix
1048
Chapter 147. Maximum XOR value in matrix
Output :
Source
https://www.geeksforgeeks.org/maximum-xor-value-matrix/
1049
Chapter 148
Consstraint :
n <= 50
m <= 50
-50 <= x1, x2, .. xn <= 50
Examples :
Input : n = 2, m = 2
arr[] = {1, 2, 3, 4}
Output : Maximum : 25
Minimum : 21
The expression is (x1 + x2) * (y1 + y2) and
the given integers are 1, 2, 3 and 4. Then
maximum value is (1 + 4) * (2 + 3) = 25
whereas minimum value is (4 + 3) * (2 + 1)
= 21.
Input : n = 3, m = 1
arr[] = {1, 2, 3, 4}
Output : Maximum : 24
Minimum : 9
1050
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
C++
1051
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
// initialize the dp array to 01
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = min(n, i + 1); k >= 1; k--) {
for (int j = 0; j < MAX * MAX + 1; j++) {
if (dp[k - 1][j])
dp[k][j + arr[i]] = 1;
}
}
}
int max_value = -INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++) {
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n][i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = max(max_value, temp * (sum - temp));
min_value = min(min_value, temp * (sum - temp));
}
}
cout << "Maximum Value: " << max_value
<< "\n"
<< "Minimum Value: "
<< min_value << endl;
}
// Driver Code
int main()
{
1052
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
int n = 2, m = 2;
int arr[] = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
return 0;
}
Java
1053
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
1054
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
Python3
1055
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
C#
1056
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
{
sum += arr[i];
// shifting the integers by 50
// so that they become positive
arr[i] += 50;
}
// dp[i][j] represents true if sum
// j can be reachable by choosing
// i numbers
bool[,] dp = new bool[MAX+1, MAX * MAX + 1];
dp[0,0] = true;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = Math.Min(n, i + 1); k >= 1; k--)
{
for (int j = 0; j < MAX * MAX + 1; j++)
{
if (dp[k - 1,j])
dp[k,j + arr[i]] = true;
}
}
}
double max_value = -1 * INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++)
{
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n,i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = Math.Max(max_value, temp *
1057
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
(sum - temp));
min_value = Math.Min(min_value, temp *
(sum - temp));
}
}
Console.WriteLine("Maximum Value: " + max_value
+ "\n" + "Minimum Value: " + min_value + "\n");
}
// Driver Code
public static void Main()
{
int n = 2, m = 2;
int []arr = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to find the
// maximum and minimum values
// of an Algebraic expression
// of given form
function minMaxValues($arr, $n, $m)
{
// Finding sum of
// array elements
$sum = 0;
$INF = 1000000000;
$MAX = 50;
for ($i = 0; $i < ($n + $m); $i++)
{
$sum += $arr[$i];
// shifting the integers by 50
// so that they become positive
$arr[$i] += 50;
}
// dp[i][j] represents true
// if sum j can be reachable
1058
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
1059
Chapter 148. Maximum and Minimum Values of an Algebraic Expression
Output :
Maximum Value: 25
Minimum Value: 21
Source
https://www.geeksforgeeks.org/maximum-minimum-values-algebraic-expression/
1060
Chapter 149
Naive Method :
We find maximum and minimum of matrix separately using linear search. Number of com-
parison needed is n2 for finding minimum and n2 for finding the maximum element. The
total comparison is equal to 2n2 .
Pair Comparison (Efficient method):
Select two elements from the matrix one from the start of a row of the matrix another from
the end of the same row of the matrix, compare them and next compare smaller of them
to the minimum of the matrix and larger of them to the maximum of the matrix. We can
see that for two elements we need 3 compare so for traversing whole of the matrix we need
total of 3/2 n2 comparisons.
Note : This is extended form of method 3 of Maximum Minimum of Array.
C++
1061
Chapter 149. Maximum and Minimum in a square matrix.
1062
Chapter 149. Maximum and Minimum in a square matrix.
return 0;
}
Java
1063
Chapter 149. Maximum and Minimum in a square matrix.
C#
1064
Chapter 149. Maximum and Minimum in a square matrix.
}
}
}
Console.Write("Maximum = " + max +
", Minimum = " + min);
}
// Driver code
static public void Main ()
{
int[,] arr = { {5, 9, 11},
{25, 0, 14},
{21, 6, 4} };
maxMin(arr, 3);
}
}
// This code is contributed by Shrikant13.
PHP
<?php
// PHP program for finding
// maximum and minimum in
// a matrix.
$MAX = 100;
// Finds maximum and minimum
// in arr[0..n-1][0..n-1]
// using pair wise comparisons
function maxMin($arr, $n)
{
$min = PHP_INT_MAX;
$max = PHP_INT_MIN;
// Traverses rows one by one
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j <= $n / 2; $j++)
{
// Compare elements from beginning
// and end of current row
if ($arr[$i][$j] > $arr[$i][$n - $j - 1])
{
if ($min > $arr[$i][$n - $j - 1])
1065
Chapter 149. Maximum and Minimum in a square matrix.
Output:
Source
https://www.geeksforgeeks.org/maximum-and-minimum-in-a-square-matrix/
1066
Chapter 150
// If i or j is our of boundary
If i >= n || j >= n
return 0
1067
Chapter 150. Maximum decimal value path in a binary matrix
If mat[i][j] == 1
return power(2, p) + result
Else
return result
// 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 },
1068
Chapter 150. Maximum decimal value path in a binary matrix
{ 1 ,0 ,1 ,1 },
};
cout << maxDecimalValue(mat, 0, 0, 0) << endl;
return 0;
}
Python3
PHP
<?php
1069
Chapter 150. Maximum decimal value path in a binary matrix
Output:
111
1070
Chapter 150. Maximum decimal value path in a binary matrix
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 c++ implementation of above problem using Dynamic Programming
1071
Chapter 150. Maximum decimal value path in a binary matrix
{
// 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;
}
Output:
111
1072
Chapter 150. Maximum decimal value path in a binary matrix
Source
https://www.geeksforgeeks.org/maximum-decimal-value-path-in-a-binary-matrix/
1073
Chapter 151
Maximum determinant of a
matrix with every values either
0 or n
Input : n = 3
Output : Maximum determinant = 54
Resultant Matrix :
3 3 0
0 3 3
3 0 3
Input : n = 13
Output : Maximum determinant = 4394
Resultant Matrix :
13 13 0
0 13 13
13 0 13
Explanation:
For any 3*3 matrix having elements either 0 or n, the maximum possible determinant is
2*(n^3).. Also a matrix having maximum determinant is of form:
nn0
0nn
n00
1074
Chapter 151. Maximum determinant of a matrix with every values either 0 or n
C++
1075
Chapter 151. Maximum determinant of a matrix with every values either 0 or n
Java
1076
Chapter 151. Maximum determinant of a matrix with every values either 0 or n
geeks.resMatrix(n);
}
}
// This code is contributed by vt_m.
C#
1077
Chapter 151. Maximum determinant of a matrix with every values either 0 or n
{
int n = 15;
GFG geeks=new GFG();
Console.WriteLine("Maximum Determinant = "
+ maxDet(n));
Console.WriteLine("Resultant Matrix :");
geeks.resMatrix(n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find maximum
// possible determinant of 0/n matrix.
// Function for maximum determinant
function maxDet($n)
{
return (2 * $n * $n * $n);
}
// Function to print
// resulatant matrix
function resMatrix ( $n)
{
for ($i = 0; $i < 3; $i++)
{
for ($j = 0; $j < 3; $j++)
{
// three position
// where 0 appears
if ($i == 0 && $j == 2)
echo "0 ";
else if ($i == 1 && $j == 0)
echo "0 ";
else if ($i == 2 && $j == 1)
echo "0 ";
// position where n appears
else
echo $n , " ";
}
echo "\n";
1078
Chapter 151. Maximum determinant of a matrix with every values either 0 or n
}
}
// Driver code
$n = 15;
echo "Maximum Determinant = " ,
maxDet($n);
echo "\nResultant Matrix :\n";
resMatrix($n);
// This code is contributed
// by nitin mittal.
?>
Output :
Source
https://www.geeksforgeeks.org/maximum-determinant-matrix-every-values-either-0-n/
1079
Chapter 152
A simple solution for this problem is to one by one select each row, compute sum of
elements in it and take difference from sum of next rows in forward direction. Finally
return the maximum difference. Time complexity for this approach will be O(n*m2 ).
An efficient solution solution for this problem is to first calculate the sum of all
elements of each row and store them in an auxiliary array rowSum[] and then calculate
maximum difference of two elements max(rowSum[j] – rowSum[i]) such that rowSum[i]
< rowSum[j] in linear time. See this article. In this method, we need to keep track of 2
things:
1) Maximum difference found so far (max_diff).
2) Minimum number visited so far (min_element).
C++
1080
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
1081
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
{
int m = 5, n = 4;
int mat[][MAX] = {{-1, 2, 3, 4},
{5, 3, -2, 1},
{6, 7, 2, -3},
{2, 9, 1, 4},
{2, 1, -2, 0}};
cout << maxRowDiff(mat, m, n);
return 0;
}
Java
1082
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
Python3
1083
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
# rowSum[i]<rowsum[j]
max_diff = rowSum[1] - rowSum[0]
min_element = rowSum[0]
for i in range(1, m):
# if current difference is greater
# than previous then update it
if (rowSum[i] - min_element > max_diff):
max_diff = rowSum[i] - min_element
# if new element is less than previous
# minimum element then update it so
# that we may get maximum difference
# in remaining array
if (rowSum[i] < min_element):
min_element = rowSum[i]
return max_diff
# Driver program to run the case
m = 5
n = 4
mat = [[-1, 2, 3, 4],
[5, 3, -2, 1],
[6, 7, 2, -3],
[2, 9, 1, 4],
[2, 1, -2, 0]]
print( maxRowDiff(mat, m, n))
# This code is contributed by Swetank Modi
C#
1084
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
1085
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
int m = 5, n = 4;
int [,] mat = { {-1, 2, 3, 4 },
{5, 3, -2, 1 },
{6, 7, 2, -3},
{2, 9, 1, 4 },
{2, 1, -2, 0} };
Console.Write(maxRowDiff(mat, m, n));
}
}
// This code is contributed by KRV.
PHP
<?php
// PHP program to find maximum
// difference of sum of
// elements of two rows
$MAX = 100;
// Function to find maximum
// difference of sum of
// elements of two rows such
// that second row appears
// before first row.
function maxRowDiff($mat, $m, $n)
{
global $MAX;
// auxiliary array to store
// sum of all elements
// of each row
$rowSum = array();
// calculate sum of each
// row and store it in
// rowSum array
for ($i = 0; $i < $m; $i++)
{
$sum = 0;
for ($j = 0; $j < $n; $j++)
$sum += $mat[$i][$j];
$rowSum[$i] = $sum;
}
// calculating maximum
// difference of two
// elements such that
1086
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
// rowSum[i]<rowsum[j]
$max_diff = $rowSum[1] - $rowSum[0];
$min_element = $rowSum[0];
for ($i = 1; $i < $m; $i++)
{
// if current difference
// is greater than
// previous then update it
if ($rowSum[$i] - $min_element > $max_diff)
$max_diff = $rowSum[$i] - $min_element;
// if new element is less
// than previous minimum
// element then update it
// so that we may get maximum
// difference in remaining array
if ($rowSum[$i] < $min_element)
$min_element = $rowSum[$i];
}
return $max_diff;
}
// Driver Code
$m = 5;
$n = 4;
$mat = array(array(-1, 2, 3, 4),
array(5, 3, -2, 1),
array(6, 7, 2, -3),
array(2, 9, 1, 4),
array(2, 1, -2, 0));
echo maxRowDiff($mat, $m, $n);
// This code is contributed by ajit
?>
Output:
1087
Chapter 152. Maximum difference of sum of elements in two rows in a matrix
Source
https://www.geeksforgeeks.org/maximum-difference-sum-elements-two-rows-matrix/
1088
Chapter 153
Maximum mirrors which can transfer light from bottom to right - GeeksforGeeks
A square matrix is given in which each cell represents either a blank or an obstacle. We
can place mirrors at blank positionl. All mirrors will be situated at 45 degree, i.e. they can
transfer light from bottom to right if no obstacle is there in their path.
In this question we need to count how many such mirrors can be placed in square matrix
which can transfer light from bottom to right.
Examples:
We can solve this problem by checking position of such mirrors in matrix, the mirror which
can transfer light from bottom to right will not have any obstacle in their path i.e.
if a mirror is there at index (i, j) then
there will be no obstacle at index (k, j) for all k, i < k <= N
there will be no obstacle at index (i, k) for all k, j < k <= N
Keeping above two equations in mind, we can find rightmost obstacle at every row in one
iteration of given matrix and we can find bottommost obstacle at every column in another
iteration of given matrix. After storing these indices in separate array we can check at
each index whether it satisfies no obstacle condition or not and then increase the count
1089
Chapter 153. Maximum mirrors which can transfer light from bottom to right
accordingly.
Below is implemented solution on above concept which requires O(N^2) time and O(N)
extra space.
1090
Chapter 153. Maximum mirrors which can transfer light from bottom to right
int res = 0; // Initialize result
// if there is not obstacle on right or below,
// then mirror can be placed to transfer light
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
/* if i > vertical[j] then light can from bottom
if j > horizontal[i] then light can go to right */
if (i > vertical[j] && j > horizontal[i])
{
/* uncomment this code to print actual mirror
position also
cout << i << " " << j << endl; */
res++;
}
}
}
return res;
}
// Driver code to test above method
int main()
{
int N = 5;
// B - Blank O - Obstacle
string mat[N] = {"BBOBB",
"BBBBO",
"BBBBB",
"BOOBO",
"BBBOB"
};
cout << maximumMirrorInMatrix(mat, N) << endl;
return 0;
}
Output:
1091
Chapter 153. Maximum mirrors which can transfer light from bottom to right
Source
https://www.geeksforgeeks.org/maximum-mirrors-can-transfer-light-bottom-right/
1092
Chapter 154
Maximum number of customers that can be satisfied with given quantity - GeeksforGeeks
A new variety of rice has been brought in supermarket and being available for the first
time, the quantity of this rice is limited. Each customer demands the rice in two different
packaging of size a and size b. The sizes a and b are decided by staff as per the demand.
Given the size of the packets a and b, the total quantity of rice available d and the number
of customers n, find out maximum number of customers that can be satisfied with the given
quantity of rice.
Display the total number of customers that can be satisfied and the index of customers that
can be satisfied.
Note: If a customer orders 2 3, he requires 2 packets of size a and 3 packets of size b.
Assume indexing of customers starts from 1.
Input:
The first line of input contains two integers n and d; next line contains two integers a and b.
Next n lines contain two integers for each customer denoting total number of bags of size a
and size b that customer requires.
Output:
Print maximum number of customers that can be satisfied and in next line print the space
separated indexes of satisfied customers.
Examples:
Input : n = 5, d = 5
a = 1, b = 1
2 0
1093
Chapter 154. Maximum number of customers that can be satisfied with given quantity
3 2
4 4
10 0
0 1
Output : 2
5 1
Input : n = 6, d = 1000000000
a = 9999, b = 10000
10000 9998
10000 10000
10000 10000
70000 70000
10000 10000
10000 10000
Output : 5
1 2 3 5 6
Explanation:
In first example, the order of customers according to their demand is:
Customer ID Demand
5 1
1 2
2 5
3 8
4 10
From this, it can easily be concluded that only customer 5 and customer 1 can be satisfied
for total demand of 1 + 2 = 3. Rest of the customer cannot purchase the remaining rice, as
their demand is greater than available amount.
Approach:
In order to meet the demand of maximum number of customers we must start with the
customer with minimum demand so that we have maximum amount of rice left to satisfy
remaining customers. Therefore, sort the customers according to the increasing order of
demand so that maximum number of customers can be satisfied.
Below is the implementation of above approach:
1094
Chapter 154. Maximum number of customers that can be satisfied with given quantity
1095
Chapter 154. Maximum number of customers that can be satisfied with given quantity
Output:
2
5 1
Source
https://www.geeksforgeeks.org/maximum-number-customers-can-satisfied-given-quantity/
1096
Chapter 155
Given two integers and , where . Find the maximum number of one’s in
a binary matrix can have such that every sub-matrix of size has atleast
one cell as zero.
Examples:
Input:5 3
Output: Maximum number of ones = 24
The matrix will be:
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
Input:5 2
Output: Maximum number of ones = 21
The matrix will be:
1 1 1 1 1
1 0 1 0 1
1 1 1 1 1
1 0 1 0 1
1 1 1 1 1
Approach The problem can be solved using a greedy approach. Place a zero at the right-
bottom corner of the first square sub-matrix, i.e. the sub-matrix with coordinates (1, 1) and
1097
Chapter 155. Maximum number of ones in a N*N matrix with given constraints
(x, x), and create the rest of the matrix symmetrically, we can get the minimum number
of zeros, or, the maximum number of ones. Thus by observing, a common conclusion can
be drawn that there are number of zeroes, in the minimum arrangement. The
1098
Chapter 155. Maximum number of ones in a N*N matrix with given constraints
Java
Python3
1099
Chapter 155. Maximum number of ones in a N*N matrix with given constraints
C#
1100
Chapter 155. Maximum number of ones in a N*N matrix with given constraints
PHP
<?php
// PHP program to get Maximum
// Number of ones in a matrix
// with given constraints
// Function that returns
// the maximum number of ones
function getMaxOnes($n, $x)
{
// Minimum number
// of zeroes
$zeroes = (int)($n / $x);
$zeroes = $zeroes *
$zeroes;
// Totol cells = square of
// the size of the matrices
1101
Chapter 155. Maximum number of ones in a N*N matrix with given constraints
$total = $n * $n;
// Intialising
// the answer
$ans = $total - $zeroes;
return $ans;
}
// Driver code
// Intitalising
// the variables
$n = 5;
$x = 2;
echo getMaxOnes($n, $x);
// This code is contributed
// by akt_mit
?>
Output:
21
Source
https://www.geeksforgeeks.org/maximum-number-of-ones-in-a-nn-matrix-with-given-constraints/
1102
Chapter 156
Input : mat[][] = 10 10 2 0 20 4
1 0 0 30 2 5
0 10 4 0 2 0
1 0 2 20 0 4
Output : 74
The maximum sum path is 20-30-4-20.
Input : mat[][] = 1 2 3
9 8 7
4 5 6
Output : 17
The maximum sum path is 3-8-6.
We are given a matrix of N * M. To find max path sum first we have to find max value in
first row of matrix. Store this value in res. Now for every element in matrix update element
with max value which can be included in max path. If the value is greater then res then
update res. In last return res which consists of max path sum value.
C++
1103
Chapter 156. Maximum path sum in matrix
Java
1104
Chapter 156. Maximum path sum in matrix
1105
Chapter 156. Maximum path sum in matrix
{ 1, 0, 0, 30, 2, 5 },
{ 0, 10, 4, 0, 2, 0 },
{ 1, 0, 2, 20, 0, 4 }
};
System.out.println(findMaxPath(mat));
}
}
// Contributed by Pramod Kumar
Python 3
1106
Chapter 156. Maximum path sum in matrix
C#
1107
Chapter 156. Maximum path sum in matrix
Output:
74
1108
Chapter 156. Maximum path sum in matrix
Source
https://www.geeksforgeeks.org/maximum-path-sum-matrix/
1109
Chapter 157
Maximum path sum that starting with any cell of 0-th row and ending with any cell of
(N-1)-th row - GeeksforGeeks
Given a N X N matrix Mat[N][N] of positive integers. There are only three possible moves
from a cell (i, j)
1. (i+1, j)
2. (i+1, j-1)
3. (i+1, j+1)
Starting from any column in row 0, return the largest sum of any of the paths up to row
N-1.
Examples:
1110
Chapter 157. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
i = N-1, j = 0 to N -1
int MaximumPath(Mat[][N], I, j)
If we draw recursion tree of above recursive solution, we can observe overlapping subprob-
lems. Since the problem has overlapping subproblems, we can solve it efficiently using
Dynamic Programming. Below is Dynamic Programming based solution.
CPP
1111
Chapter 157. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
Java
1112
Chapter 157. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
class GFG {
static int N = 4;
// function find maximum sum path
static int MaximumPath(int Mat[][])
{
int result = 0;
// creat 2D matrix to store the sum
// of the path
int dp[][] = new int[N][N + 2];
// initialize all dp matrix as '0'
for (int[] rows : dp)
Arrays.fill(rows, 0);
// copy all element of first column into
// 'dp' first column
for (int i = 0; i < N; i++)
dp[0][i + 1] = Mat[0][i];
for (int i = 1; i < N; i++)
for (int j = 1; j <= N; j++)
dp[i][j] = Math.max(dp[i - 1][j - 1],
Math.max(dp[i - 1][j],
dp[i - 1][j + 1])) +
Mat[i][j - 1];
// Find maximum path sum that end ups
// at any column of last row 'N-1'
for (int i = 0; i <= N; i++)
result = Math.max(result, dp[N - 1][i]);
// return maximum sum path
return result;
}
// driver code
public static void main(String arg[])
{
int Mat[][] = { { 4, 2, 3, 4 },
{ 2, 9, 1, 10 },
{ 15, 1, 3, 0 },
{ 16, 92, 41, 44 } };
System.out.println(MaximumPath(Mat));
}
1113
Chapter 157. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
}
// This code is contributed by Anant Agarwal.
Python3
1114
Chapter 157. Maximum path sum that starting with any cell of 0-th row and ending with
any cell of (N-1)-th row
# This code is contributed by Soumen Ghosh.
Output:
120
Source
https://www.geeksforgeeks.org/maximum-path-sum-starting-cell-0-th-row-ending-cell-n-1-th-row/
1115
Chapter 158
1116
Chapter 158. Maximum points collected by two persons allowed to meet once
P1 needs to move from top left (0, 0) to bottom right (n-1, m-1). P1 can move right and
down, i.e., from A[i][j] to A[i][j+1] or A[i+1][j]
P2 needs to move from bottom left (n-1, 0) to top right (0, m-1). P2 can move right and
up, i.e., from A[i][j] to A[i][j+1] or A[i-1][j].
The idea is to consider every point as a meeting point and find maximum of all meeting
points. When we consider a point A[i][j] as meeting point, we need to have following four
values to find maximum total points collected when A[i][j] is meeting point.
1) Points collected by P1 from (0, 0) to (i, j).
2) Points collected by P1 from (i, j) to (n-1, m-1).
3) Points collected by P2 from (n-1, 0) to (i, j).
4) Points collected by P2 from (i, j) to (0, m-1).
We can compute above four values using Dynamic Programming. Once we have above four
values for every point, we can find maximum points at every meeting point.
For every meeting points, there are two possible values to reach it and leave it as we are
allowed to have only one meeting point.
1) P1 reaches it through a right move and p2 through a up move and they leave same way
also.
2) P1 reaches it through a down move and p2 through a right move and they leave same
way also.
We take maximum of above two values to find optimal points at this meeting point.
Finally, we return maximum of all meeting points.
1117
Chapter 158. Maximum points collected by two persons allowed to meet once
1118
Chapter 158. Maximum points collected by two persons allowed to meet once
// Driver code
int main()
{
//input the calories burnt matrix
int A[][M] = {{100, 100, 100},
{100, 1, 100},
{100, 100, 100}};
cout << "Max Points : " << findMaxPoints(A);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-points-collected-by-two-persons-allowed-to-meet-once/
1119
Chapter 159
Maximum points from top left of matrix to bottom right and return back - GeeksforGeeks
Given a matrix of size N X M consisting of ‘#’, ‘.’ and ‘*’. ‘#’ means blocked path, ‘.’
means walkable path and ‘*’ means point you have to collect. Now consider you are at top
left of the matrix. You have to reach bottom right of the matrix and come back to top left.
When you are moving top left to bottom right, you are allowed to walk right or down. And
when you are moving bottom right to top left, you are allowed to walk left or up. The task
is find the maximum points you can grab during your whole journey. Points once taken will
be converted into ‘.’ i.e walkable path.
Examples:
Input : N = 3, M = 4
****
.##.
.##.
****
Output : 8
Input : N = 9, M = 7
*........
.....**#.
..**...#*
..####*#.
.*.#*.*#.
...#**...
*........
1120
Chapter 159. Maximum points from top left of matrix to bottom right and return back
Output : 7
If you consider two paths – one from (0, 0) to (N – 1, M – 1) and another from (N – 1, M –
1) to (0, 0) and collect maximum * in each path. You might end up with wrong answer. If
you add the answer of both the paths independently, you will be calculating the intersecting
points once again while backtracking. Essentially, ending up with the same path. Even if
you keep a visited array, marking every * on the first path, you will still not end up with
the correct answer.
Consider the following example:
total * collected is 7.
Whereas the maximum points collected can be 8 by following paths.
1121
Chapter 159. Maximum points from top left of matrix to bottom right and return back
1122
Chapter 159. Maximum points from top left of matrix to bottom right and return back
#define M 5
#define inf 100000
using namespace std;
// Calculating the points at a (row1, col1) &&
// (row2, col2) from path1 && path2
int cost(char grid[][M], int row1, int col1,
int row2, int col2)
{
// If both path is at same cell
if (row1 == row2 && col1 == col2) {
// If the cell contain *, return 1
if (grid[row1][col1] == '*')
return 1;
// else return 0.
return 0;
}
int ans = 0;
// If path 1 contain *, add to answer.
if (grid[row1][col1] == '*')
ans++;
// If path contain *, add to answer.
if (grid[row2][col2] == '*')
ans++;
return ans;
}
// Calculate the maximum points that can be
// collected.
int solve(int n, int m, char grid[][M],
int dp[MAX][MAX][MAX], int row1,
int col1, int row2)
{
int col2 = (row1 + col1) - (row2);
// If both path reach the bottom right cell
if (row1 == n - 1 && col1 == m - 1 &&
row2 == n - 1 && col2 == m - 1)
return 0;
// If moving out of grid
if (row1 >= n || col1 >= m ||
1123
Chapter 159. Maximum points from top left of matrix to bottom right and return back
1124
Chapter 159. Maximum points from top left of matrix to bottom right and return back
Output:
Source
https://www.geeksforgeeks.org/maximum-points-top-left-matrix-bottom-right-return-back/
1125
Chapter 160
Input : n = 4
{{6, 2, 3 4},
{5, 4, 3, 1},
{7, 4, 5, 6},
{8, 3, 1, 0}}
Output : 1680
Explanation:
Multiplication of 6 5 7 8 produces maximum
result and all element are adjacent to
each other in one direction
Input : n = 5
{{1, 2, 3, 4, 5},
{6, 7, 8, 9, 1},
{2, 3, 4, 5, 6},
{7, 8, 9, 1, 0},
{9, 6, 4, 2, 3}}
1126
Chapter 160. Maximum product of 4 adjacent elements in matrix
Output: 3024
Explanation:
Multiplication of 6 7 8 9 produces maximum
result and all elements are adjacent to
each other in one direction.
Asked in : Tolexo
Approach:
1. Group 4 elements which are adjacent to each other in each row and calculate their
maximum result.
2. Group 4 elements which are adjacent to each other in each column and calculate their
maximum results.
3. Group 4 elements which are adjacent to each other in diagonal and calculate their
maximum results.
4. Group 4 elements which are adjacent to each other in anti diagonal and calculate their
maximum results.
5. Compare of all calculated maximum results.
Below is the implementation of above approach:
C++
1127
Chapter 160. Maximum product of 4 adjacent elements in matrix
{
result = arr[i][j] * arr[i][j - 1] *
arr[i][j - 2] * arr[i][j - 3];
if (max < result)
max = result;
}
// check the maximum product
// in vertical row.
if ((i - 3) >= 0)
{
result = arr[i][j] * arr[i - 1][j] *
arr[i - 2][j] * arr[i - 3][j];
if (max < result)
max = result;
}
// check the maximum product in
// diagonal and anti - diagonal
if ((i - 3) >= 0 && (j - 3) >= 0)
{
result = arr[i][j] * arr[i - 1][j - 1] *
arr[i - 2][j - 2] * arr[i - 3][j - 3];
if (max < result)
max = result;
}
}
}
return max;
}
// driver code
int main()
{
/* int arr[][4] = {{6, 2, 3, 4},
{5, 4, 3, 1},
{7, 4, 5, 6},
{8, 3, 1, 0}};*/
/* int arr[][5] = {{1, 2, 1, 3, 4},
{5, 6, 3, 9, 2},
{7, 8, 8, 1, 2},
{1, 0, 7, 9, 3},
{3, 0, 8, 4, 9}};*/
1128
Chapter 160. Maximum product of 4 adjacent elements in matrix
int arr[][5] = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 1},
{2, 3, 4, 5, 6},
{7, 8, 9, 1, 0},
{9, 6, 4, 2, 3}};
cout << FindMaxProduct(arr, n);
return 0;
}
Java
1129
Chapter 160. Maximum product of 4 adjacent elements in matrix
if (max < result)
max = result;
}
// check the maximum product in
// diagonal and anti - diagonal
if ((i - 3) >= 0 && (j - 3) >= 0)
{
result = arr[i][j] * arr[i - 1][j - 1] *
arr[i - 2][j - 2] * arr[i - 3][j - 3];
if (max < result)
max = result;
}
}
}
return max;
}
// Driver code
public static void main(String[] args)
{
/* int arr[][4] = {{6, 2, 3, 4},
{5, 4, 3, 1},
{7, 4, 5, 6},
{8, 3, 1, 0}};*/
/* int arr[][5] = {{1, 2, 1, 3, 4},
{5, 6, 3, 9, 2},
{7, 8, 8, 1, 2},
{1, 0, 7, 9, 3},
{3, 0, 8, 4, 9}};*/
int arr[][] = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 1},
{2, 3, 4, 5, 6},
{7, 8, 9, 1, 0},
{9, 6, 4, 2, 3}};
System.out.print(FindMaxProduct(arr, n));
}
}
// This code is contributed by Anant Agarwal.
C#
1130
Chapter 160. Maximum product of 4 adjacent elements in matrix
1131
Chapter 160. Maximum product of 4 adjacent elements in matrix
PHP
<?php
// PHP program to find out the maximum product
// in the matrix which four elements are
// adjacent to each other in one direction
$n = 5;
// function to find max product
function FindMaxProduct( $arr, $n)
{
$max = 0; $result;
// iterate the rows.
for ( $i = 0; $i < $n; $i++)
{
// iterate the columns.
for ( $j = 0; $j < $n; $j++)
{
1132
Chapter 160. Maximum product of 4 adjacent elements in matrix
// check the maximum product
// in horizontal row.
if (($j - 3) >= 0)
{
$result = $arr[$i][$j] *
$arr[$i][$j - 1] *
$arr[$i][$j - 2] *
$arr[$i][$j - 3];
if ($max < $result)
$max = $result;
}
// check the maximum product
// in vertical row.
if (($i - 3) >= 0)
{
$result = $arr[$i][$j] *
$arr[$i - 1][$j] *
$arr[$i - 2][$j] *
$arr[$i - 3][$j];
if ($max < $result)
$max = $result;
}
// check the maximum product in
// diagonal and anti - diagonal
if (($i - 3) >= 0 and ($j - 3) >= 0)
{
$result = $arr[$i][$j] *
$arr[$i - 1][$j - 1] *
$arr[$i - 2][$j - 2] *
$arr[$i - 3][$j - 3];
if ($max < $result)
$max = $result;
}
}
}
return $max;
}
// Driver Code
$arr = array(array(1, 2, 3, 4, 5),
array(6, 7, 8, 9, 1),
1133
Chapter 160. Maximum product of 4 adjacent elements in matrix
array(2, 3, 4, 5, 6),
array(7, 8, 9, 1, 0),
array(9, 6, 4, 2, 3));
echo FindMaxProduct($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
3024
Source
https://www.geeksforgeeks.org/maximum-product-of-4-adjacent-elements-in-matrix/
1134
Chapter 161
Input : 0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Output : 1 1 1 1
1 1 1 1
We have discussed a dynamic programming based solution for finding largest square with
1s.
In this post an interesting method is discussed that uses largest rectangle under histogram
as a subroutine. Below are steps. The idea is to update each column of a given row with
corresponding column of previous row and find largest histogram area for for that row.
1135
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s
Illustration :
Below is the implementation. It is strongly recommended to refer this post first as most of
the code taken from there.
C++
1136
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s
result.push(i++);
else
{
// If this bar is lower than top of stack, then
// calculate area of rectangle with stack top as
// the smallest (or minimum height) bar. 'i' is
// 'right index' for the top and element before
// top in stack is 'left index'
top_val = row[result.top()];
result.pop();
area = top_val * i;
if (!result.empty())
area = top_val * (i - result.top() - 1 );
max_area = max(area, max_area);
}
}
// Now pop the remaining bars from stack and calculate area
// with every popped bar as the smallest bar
while (!result.empty())
{
top_val = row[result.top()];
result.pop();
area = top_val * i;
if (!result.empty())
area = top_val * (i - result.top() - 1 );
max_area = max(area, max_area);
}
return max_area;
}
// Returns area of the largest rectangle with all 1s in A[][]
int maxRectangle(int A[][C])
{
// Calculate area for first row and initialize it as
// result
int result = maxHist(A[0]);
// iterate over row to find maximum rectangular area
// considering each row as histogram
for (int i = 1; i < R; i++)
{
for (int j = 0; j < C; j++)
1137
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s
Java
1138
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s
1139
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s
Output :
1140
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s
Source
https://www.geeksforgeeks.org/maximum-size-rectangle-binary-sub-matrix-1s/
1141
Chapter 162
Algorithm:
Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary
size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all
1s including M[i][j] where M[i][j] is the rightmost and bottommost entry in sub-matrix.
1142
Chapter 162. Maximum size square sub-matrix with all 1s
sub-matrix of M[][]
For the given M[R][C] in above example, constructed S[R][C] would be:
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 2 2 0
1 2 2 3 1
0 0 0 0 0
The value of maximum entry in above matrix is 3 and coordinates of the entry are (4, 3).
Using the maximum value and its coordinates, we can find out the required sub-matrix.
C/C++
1143
Chapter 162. Maximum size square sub-matrix with all 1s
/* Find the maximum entry, and indexes of maximum entry
in S[][] */
max_of_s = S[0][0]; max_i = 0; max_j = 0;
for(i = 0; i < R; i++)
{
for(j = 0; j < C; j++)
{
if(max_of_s < S[i][j])
{
max_of_s = S[i][j];
max_i = i;
max_j = j;
}
}
}
printf("Maximum size sub-matrix is: \n");
for(i = max_i; i > max_i - max_of_s; i--)
{
for(j = max_j; j > max_j - max_of_s; j--)
{
printf("%d ", M[i][j]);
}
printf("\n");
}
}
/* UTILITY FUNCTIONS */
/* Function to get minimum of three values */
int min(int a, int b, int c)
{
int m = a;
if (m > b)
m = b;
if (m > c)
m = c;
return m;
}
/* Driver function to test above functions */
int main()
{
bool M[R][C] = {{0, 1, 1, 0, 1},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{1, 1, 1, 1, 0},
{1, 1, 1, 1, 1},
1144
Chapter 162. Maximum size square sub-matrix with all 1s
{0, 0, 0, 0, 0}};
printMaxSubSquare(M);
getchar();
}
Java
1145
Chapter 162. Maximum size square sub-matrix with all 1s
Python3
1146
Chapter 162. Maximum size square sub-matrix with all 1s
Output:
Time Complexity: O(m*n) where m is number of rows and n is number of columns in the
given matrix.
1147
Chapter 162. Maximum size square sub-matrix with all 1s
Auxiliary Space: O(m*n) where m is number of rows and n is number of columns in the
given matrix.
Algorithmic Paradigm: Dynamic Programming
Source
https://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
1148
Chapter 163
Maximum sub-matrix area having count of 1’s one more than count of 0’s - GeeksforGeeks
Given a N x N binary matrix. The problem is finding the maximum area sub-matrix having
a count of 1’s one more than count of 0’s.
Examples:
Naive Approach: Check every possible rectangle in given 2D matrix. This solution re-
quires 4 nested loops and the time complexity of this solution would be O(n^4).
Efficient Approach: An efficient approach will be to use Longest subarray having count
of 1s one more than count of 0s which reduces the time complexity to O(n^3). The idea is
to fix the left and right columns one by one and find the maximum length contiguous rows
having the count of 1’s one more than the count of 0’s for every left and right column pair.
Find top and bottom row numbers (which have a maximum length) for every fixed left and
right column pair. To find the top and bottom row numbers, calculate the sum of elements
1149
Chapter 163. Maximum sub-matrix area having count of 1’s one more than count of 0’s
in every row from left to right and store these sums in an array say temp[] (consider 0 as -1
while adding it). So temp[i] indicates the sum of elements from left to right in row i. Using
the approach in Longest subarray having count of 1s one more than count of 0s , temp[]
array is used to get the maximum length subarray of temp[] having count of 1’s one more
than a count of 0’s by obtaining the start and end row numbers, then these values can be
used to find maximum possible area with left and right as boundary columns. To get the
overall maximum area, compare this area with the maximum area so far.
Below is the implementation of the above approach:
1150
Chapter 163. Maximum sub-matrix area having count of 1’s one more than count of 0’s
1151
Chapter 163. Maximum sub-matrix area having count of 1’s one more than count of 0’s
// Compare with maximum area
// so far and accordingly update the
// final variables
if ((len != 0) && (maxArea < (finish - start + 1)
* (right - left + 1))) {
finalLeft = left;
finalRight = right;
finalTop = start;
finalBottom = finish;
maxArea = (finish - start + 1) * (right - left + 1);
}
}
}
// Print final values
cout << "(Top, Left): (" << finalTop << ", "
<< finalLeft << ")\n";
cout << "(Bottom, Right): (" << finalBottom << ", "
<< finalRight << ")\n";
cout << "Maximum area: " << maxArea;
}
// Driver Code
int main()
{
int mat[SIZE][SIZE] = { { 1, 0, 0, 1 },
{ 0, 1, 1, 1 },
{ 1, 0, 0, 0 },
{ 0, 1, 0, 1 } };
int n = 4;
largestSubmatrix(mat, n);
return 0;
}
Output:
1152
Chapter 163. Maximum sub-matrix area having count of 1’s one more than count of 0’s
Source
https://www.geeksforgeeks.org/maximum-sub-matrix-area-having-count-of-1s-one-more-than-count-of-0s/
1153
Chapter 164
Maximum sum in a 2 x n grid such that no two elements are adjacent - GeeksforGeeks
Given a rectangular grid of dimension 2 x n. We need to find out the maximum sum such
that no two chosen numbers are adjacent, vertically, diagonally or horizontally.
Examples:
Input : 1 4 5
2 0 0
Output : 7
If we start from 1 then we can add only 5 or 0.
So max_sum = 6 in this case.
If we select 2 then also we can add only 5 or 0.
So max_sum = 7 in this case.
If we select from 4 or 0 then there is no further
elements can be added.
So, Max sum is 7.
Input : 1 2 3 4 5
6 7 8 9 10
Output : 24
This problem is an extension of Maximum sum such that no two elements are adjacent.
Only thing to be changed is to take maximum element of both row of a particular column.
We traverse column by column and maintain maximum sum considering two cases.
1) An element of current column is included. In this case we take maximum of two elements
1154
Chapter 164. Maximum sum in a 2 x n grid such that no two elements are adjacent
in current column.
2) An element of current column is excluded (or not included)
Below is the implementation of above steps.
C++
1155
Chapter 164. Maximum sum in a 2 x n grid such that no two elements are adjacent
int n = 5;
cout << maxSum(grid, n);
return 0;
}
Java
1156
Chapter 164. Maximum sum in a 2 x n grid such that no two elements are adjacent
{ 6, 7, 8, 9, 10}};
int n = 5;
System.out.println(maxSum(grid, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Output:
24
Source
https://www.geeksforgeeks.org/maximum-sum-2-x-n-grid-no-two-elements-adjacent/
1157
Chapter 165
Input :
1 2 3
1 2 3
7 8 9
Output : 14 (2 + 3 + 9) (values we
are adding are strictly increasing)
Input :
4 2 3
3 2 1
1 2 2
Output : -1
(No subsequent increasing elements
can be picked from consecutive rows)
Approach :- One can simply run the loop from last row, get the greatest element from
there say it prev_max, and keep record for the minimum difference among the elements of
the row just above it, if any element found with positive difference, then add it to prev_max
else print -1. Continue the same process for every row.
C++
1158
Chapter 165. Maximum sum of elements from each row in the matrix
Java
1159
Chapter 165. Maximum sum of elements from each row in the matrix
1160
Chapter 165. Maximum sum of elements from each row in the matrix
{4, 5, 6},
{7, 8, 9}};
System.out.println(getGreatestSum(a));
int b[][] = {{4, 5, 6},
{4, 5, 6},
{4, 5, 6}};
System.out.println(getGreatestSum(b));
}
}
// This code is contributed by Anant Agarwal.
Python3
1161
Chapter 165. Maximum sum of elements from each row in the matrix
prev_max = curr_max
sum =sum+ prev_max
return sum
# Driver code
a= [ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ] ]
print(getGreatestSum(a))
b = [ [ 4, 5, 6 ],
[ 4, 5, 6 ],
[ 4, 5, 6 ] ]
print(getGreatestSum(b))
# This code is contributed
# by Anant Agarwal.
C#
1162
Chapter 165. Maximum sum of elements from each row in the matrix
PHP
<?php
// PHP Program to find
// row-wise maximum element
// sum considering elements
// in increasing order.
$N = 3;
1163
Chapter 165. Maximum sum of elements from each row in the matrix
// Function to perform given task
function getGreatestSum( $a)
{
global $N;
// Getting the maximum
// element from last row
$prev_max = 0;
for ($j = 0; $j < $N; $j++)
if ($prev_max < $a[$N - 1][$j])
$prev_max = $a[$N - 1][$j];
// Comparing it with the
// elements of above rows
$sum = $prev_max;
for ($i = $N - 2; $i >= 0; $i--)
{
// Maximum of current row.
$curr_max = PHP_INT_MIN;
for ( $j = 0; $j < $N; $j++)
if ($prev_max > $a[$i][$j] and
$a[$i][$j] > $curr_max)
$curr_max = $a[$i][$j];
// If we could not an element
// smaller than prev_max.
if ($curr_max == PHP_INT_MAX)
return -1;
$prev_max = $curr_max;
$sum += $prev_max;
}
return $sum;
}
// Driver code
$a = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
echo getGreatestSum($a) ,"\n";
$b = array(array(4, 5, 6),
array(4, 5, 6),
array(4, 5, 6));
1164
Chapter 165. Maximum sum of elements from each row in the matrix
Output :
18
15
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-sum-elements-row-matrix/
1165
Chapter 166
Examples:
Input : 1 1 1 0 0
0 1 0 0 0
1 1 1 0 0
0 0 0 0 0
0 0 0 0 0
Output : 7
Below is the hour glass with
maximum sum:
1 1 1
1
1 1 1
Input : 0 3 0 0 0
0 1 0 0 0
1 1 1 0 0
1166
Chapter 166. Maximum sum of hour glass in matrix
0 0 2 4 4
0 0 0 2 4
Output : 11
Below is the hour glass wuth
maximum sum
1 0 0
4
0 2 4
It is evident from definition of hour glass that number of rows and number of columns must
be greater than 3. If we count total number of hour glasses in a matrix, we can say that
the count is equal to count of possible top left cells in hour glass. Number of top-left cells
in a hour glass is equal to (R-2)*(C-2). Therefore, in a matrix total number of hour glass is
(R-2)*(C-2)
mat[][] = 2 3 0 0 0
0 1 0 0 0
1 1 1 0 0
0 0 2 4 4
0 0 0 2 0
Possible hour glass are :
2 3 0 3 0 0 0 0 0
1 0 0
1 1 1 1 1 0 1 0 0
0 1 0 1 0 0 0 0 0
1 1 0
0 0 2 0 2 4 2 4 4
1 1 1 1 1 0 1 0 0
0 2 4
0 0 0 0 0 2 0 2 0
We consider all top left cells of hour glasses one by one. For every cell, we compute sum of
hour glass formed by it. Finally we return maximum sum.
Below is the implementation of above idea :
C++
1167
Chapter 166. Maximum sum of hour glass in matrix
Java
1168
Chapter 166. Maximum sum of hour glass in matrix
import java.io.*;
class GFG {
static int R = 5;
static int C = 5;
// Returns maximum sum of
// hour glass in ar[][]
static int findMaxSum(int [][]mat)
{
if (R < 3 || C < 3)
return -1;
// Here loop runs (R-2)*(C-2)
// times considering different
// top left cells of hour glasses.
int max_sum = Integer.MIN_VALUE;
for (int i = 0; i < R - 2; i++)
{
for (int j = 0; j < C - 2; j++)
{
// Considering mat[i][j] as top
// left cell of hour glass.
int sum = (mat[i][j] + mat[i][j + 1] +
mat[i][j + 2]) + (mat[i + 1][j + 1]) +
(mat[i + 2][j] + mat[i + 2][j + 1] +
mat[i + 2][j + 2]);
// If previous sum is less then
// current sum then update
// new sum in max_sum
max_sum = Math.max(max_sum, sum);
}
}
return max_sum;
}
// Driver code
static public void main (String[] args)
{
int [][]mat = {{1, 2, 3, 0, 0},
{0, 0, 0, 0, 0},
{2, 1, 4, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0}};
int res = findMaxSum(mat);
if (res == -1)
1169
Chapter 166. Maximum sum of hour glass in matrix
System.out.println("Not possible");
else
System.out.println("Maximum sum of hour glass = "
+ res);
}
}
// This code is contributed by vt_m .
C#
1170
Chapter 166. Maximum sum of hour glass in matrix
}
return max_sum;
}
// Driver code
static public void Main(String[] args)
{
int [,]mat = {{1, 2, 3, 0, 0},
{0, 0, 0, 0, 0},
{2, 1, 4, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0}};
int res = findMaxSum(mat);
if (res == -1)
Console.WriteLine("Not possible");
else
Console.WriteLine("Maximum sum of hour glass = "
+ res);
}
}
// This code is contributed by vt_m .
Output:
Reference :
http://stackoverflow.com/questions/38019861/hourglass-sum-in-2d-array
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-sum-hour-glass-matrix/
1171
Chapter 167
{5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
Algorithm: The idea is to find maximum sum or all paths starting with every cell of first
row and finally return maximum of all values in first row. We use Dynamic Programming
as results of many subproblems are needed again and again.
C++
1172
Chapter 167. Maximum sum path in a matrix from top to bottom
1173
Chapter 167. Maximum sum path in a matrix from top to bottom
maxSum = dp[0][j];
// required maximum sum
return maxSum;
}
// Driver program to test above
int main()
{
int mat[SIZE][SIZE] = { { 5, 6, 1, 7 },
{ -2, 10, 8, -1 },
{ 3, -7, -9, 11 },
{ 12, -4, 2, 6 } };
int n = 4;
cout << "Maximum Sum = "
<< maxSum(mat, n);
return 0;
}
Java
1174
Chapter 167. Maximum sum path in a matrix from top to bottom
1175
Chapter 167. Maximum sum path in a matrix from top to bottom
C#
1176
Chapter 167. Maximum sum path in a matrix from top to bottom
PHP
<?php
// PHP implementation to find
// the maximum sum path in a matrix
$SIZE = 10;
// function to find the maximum sum
// path in a matric
function maxSum( $mat, $n)
{
// if there is a single
// element only
if ($n == 1)
return $mat[0][0];
1177
Chapter 167. Maximum sum path in a matrix from top to bottom
// dp[][] matrix to store the results
// of each iteration
$dp = array(array());
$maxSum = PHP_INT_MIN;
$max;
// base case, copying elements of
// last row
for($j = 0; $j < $n; $j++)
$dp[$n - 1][$j] = $mat[$n - 1][$j];
// building up the dp[][] matrix from
// bottom to the top row
for ( $i = $n - 2; $i >= 0; $i--)
{
for ( $j = 0; $j < $n; $j++)
{
$max = PHP_INT_MIN;
// finding the maximum
// diagonal element in the
// (i+1)th row if that cell
// exists
if ((($j - 1) >= 0) and
($max < $dp[$i + 1][$j - 1]))
$max = $dp[$i + 1][$j - 1];
if ((($j + 1) < $n) and ($max <
$dp[$i + 1][$j + 1]))
$max = $dp[$i + 1][$j + 1];
// adding that 'max' element to the
// mat[i][j] element
$dp[$i][$j] = $mat[$i][$j] + $max;
}
}
// finding the maximum value from the
// first row of dp[][]
for ( $j = 0; $j < $n; $j++)
if ($maxSum < $dp[0][$j])
$maxSum = $dp[0][$j];
// required maximum sum
return $maxSum;
1178
Chapter 167. Maximum sum path in a matrix from top to bottom
}
// Driver Code
$mat = array(array(5, 6, 1, 7),
array(-2, 10, 8, -1),
array(3, -7, -9, 11),
array(12, -4, 2, 6));
$n = 4;
echo "Maximum Sum = "
, maxSum($mat, $n);
// This code is contributed by anuj_67.
?>
Output:
Maximum Sum = 28
Source
https://www.geeksforgeeks.org/maximum-sum-path-matrix-top-bottom/
1179
Chapter 168
This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array.
The naive solution for this problem is to check every possible rectangle in given 2D array.
This solution requires 4 nested loops and time complexity of this solution would be O(n^4).
Kadane’s algorithm for 1D array can be used to reduce the time complexity to O(n^3).
The idea is to fix the left and right columns one by one and find the maximum sum
contiguous rows for every left and right column pair. We basically find top and bottom row
numbers (which have maximum sum) for every fixed left and right column pair. To find
the top and bottom row numbers, calculate sun of elements in every row from left to right
1180
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27
and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left
to right in row i. If we apply Kadane’s 1D algorithm on temp[], and get the maximum sum
subarray of temp, this maximum sum would be the maximum possible sum with left and
right as boundary columns. To get the overall maximum sum, we compare this sum with
the maximum sum so far.
1181
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27
return maxSum;
// Special Case: When all numbers in arr[] are negative
maxSum = arr[0];
*start = *finish = 0;
// Find the maximum element in array
for (i = 1; i < n; i++)
{
if (arr[i] > maxSum)
{
maxSum = arr[i];
*start = *finish = i;
}
}
return maxSum;
}
// The main function that finds maximum sum rectangle in M[][]
void findMaxSum(int M[][COL])
{
// Variables to store the final output
int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom;
int left, right, i;
int temp[ROW], sum, start, finish;
// Set the left column
for (left = 0; left < COL; ++left)
{
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column set by outer loop
for (right = left; right < COL; ++right)
{
// Calculate sum between current left and right for every row 'i'
for (i = 0; i < ROW; ++i)
temp[i] += M[i][right];
// Find the maximum sum subarray in temp[]. The kadane()
// function also sets values of start and finish. So 'sum' is
// sum of rectangle between (start, left) and (finish, right)
// which is the maximum sum with boundary columns strictly as
// left and right.
sum = kadane(temp, &start, &finish, ROW);
// Compare sum with maximum sum so far. If sum is more, then
1182
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27
Java
import java.util.*;
import java.lang.*;
import java.io.*;
/**
* Given a 2D array, find the maximum sum subarray in it
*/
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
findMaxSubMatrix(new int[][] {
{1, 2, -1, -4, -20},
{-8, -3, 4, 2, 1},
1183
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27
1184
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27
Output:
1185
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27
Source
https://www.geeksforgeeks.org/maximum-sum-rectangle-in-a-2d-matrix-dp-27/
1186
Chapter 169
0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 0
0 1 . . . . . 1 0
0 1 . b b b . 1 0
0 1 . b a b . 1 0
0 1 . b b b . 1 0
0 1 . . . . . 1 0
0 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0
where a is the center, b is a – 1, and the value will decrease as row or column increase.
Since there are multiple such sub-matrix, there are cells which are parts of more than one
such submatrix. Those cells will have the value equal to the sum of values of intersecting
submatrix. Given the value of N, m, (xi , yi , ai ), where 1 <= i <= m and ai is the value
at the center of ith concentric sub-matrix. The task is to find the maximum value in the
matrix containing submatrices.
So, after
Examples:
1187
Chapter 169. Maximum value in a matrix which contain intersecting concentric submatrix
Input : N = 10, m = 2
(x1, y1, a1) = (3, 3, 3)
(x2, y2, a2) = (7, 7, 4)
Output : 4
Maxtrix that will be form:
Input : N = 10, m = 1
(x1, y1, a1) = (4, 5, 6)
Output : 6
The idea is to make a 2D matrix mat[][] and find the value of each cell including the cell
having the intersection of multiple concentric submatrix. Now, observe value of each cell
can be find by by max(0, a – max(p – xi , q – yi )) where a is the value of at the center of
ith concentric sub-matrix, p is the row number of the cell, q is the column number of the
cell and (xi , yi ) is the center location of ith concentric sub-matrix center. So, after finding
the matrix mat[][], we will traverse the matrix to find the maximum value in the matrix.
Below is C++ implementation of this approach:
C++
1188
Chapter 169. Maximum value in a matrix which contain intersecting concentric submatrix
// maximum of x distance and y distance
int d = max(dx, dy);
// assigning the value.
c[p][q] += max(0, a[i] - d);
}
}
}
// Finding the maximum value in the formed matrix.
int res = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
res = max(res, c[i][j]);
}
}
return res;
}
// Driven Program
int main()
{
int n = 10;
int m = 2;
int x[] = { 3, 7 };
int y[] = { 3, 7 };
int a[] = { 4, 3 };
cout << maxValue(n, m, x, y, a) << endl;
return 0;
}
Java
1189
Chapter 169. Maximum value in a matrix which contain intersecting concentric submatrix
// concentric submatrix.
static int maxValue(int n, int m,
int x[], int y[],
int a[])
{
int c[][] = new int[MAXN][MAXN];
// For each center of
// concentric sub-matrix.
for (int i = 0; i < m; ++i)
{
// for each row
for (int p = 0; p < n; ++p)
{
// for each column
for (int q = 0; q < n; ++q)
{
// finding x distance.
int dx = Math.abs(p - x[i]);
// finding y distance.
int dy = Math.abs(q - y[i]);
// maximum of x distance
// and y distance
int d = Math.max(dx, dy);
// assigning the value.
c[p][q] += Math.max(0, a[i] - d);
}
}
}
// Finding the maximum
// value in the formed matrix.
int res = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
res = Math.max(res, c[i][j]);
}
}
return res;
}
1190
Chapter 169. Maximum value in a matrix which contain intersecting concentric submatrix
// Driven Code
public static void main (String[] args)
{
int n = 10;
int m = 2;
int x[] = { 3, 7 };
int y[] = { 3, 7 };
int a[] = { 4, 3 };
System.out.println(maxValue(n, m, x,
y, a));
}
}
// This code is contributed by anuj_67.
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/maximum-value-in-a-matrix-which-contain-intersecting-concentric-submatrix/
1191
Chapter 170
Maximum weight path ending at any element of last row in a matrix - GeeksforGeeks
Given a matrix of integers where every element represents weight of the cell. Find the path
having the maximum weight in matrix [N X N]. Path Traversal Rules are:
Examples:
Input : N = 5
mat[5][5] = {{ 4, 2 ,3 ,4 ,1 },
{ 2 , 9 ,1 ,10 ,5 },
{15, 1 ,3 , 0 ,20 },
{16 ,92, 41, 44 ,1},
{8, 142, 6, 4, 8} };
Output : 255
Path with max weight : 4 + 2 +15 + 92 + 142 = 255
1192
Chapter 170. Maximum weight path ending at any element of last row in a matrix
If i == 0 and j == 0
maxCost(0, 0) = mat[0][0]
If we draw recursion tree of above recursive solution, we can observe overlapping subprob-
lems. Since the problem has overlapping subproblems, we can solve it efficiently using
Dynamic Programming. Below is Dynamic Programming based solution.
C++
1193
Chapter 170. Maximum weight path ending at any element of last row in a matrix
Java
1194
Chapter 170. Maximum weight path ending at any element of last row in a matrix
dp[0][0] = mat[0][0];
// Initialize first column of total
// weight array (dp[i to N][0])
for (int i = 1; i < N; i++)
dp[i][0] = mat[i][0] + dp[i-1][0];
// Calculate rest path sum of weight matrix
for (int i = 1; i < N; i++)
for (int j = 1; j < i + 1 && j < N; j++)
dp[i][j] = mat[i][j] +
Math.max(dp[i-1][j-1],
dp[i-1][j]);
// find the max weight path sum to reach
// the last row
int result = 0;
for (int i = 0; i < N; i++)
if (result < dp[N-1][i])
result = dp[N-1][i];
// return maximum weight path sum
return result;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int mat[][] = { { 4, 1 ,5 ,6 , 1 },
{ 2 ,9 ,2 ,11 ,10 },
{ 15,1 ,3 ,15, 2 },
{ 16, 92, 41,4,3},
{ 8, 142, 6, 4, 8 }
};
int N = 5;
System.out.println("Maximum Path Sum : "+
maxCost(mat, N));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
1195
Chapter 170. Maximum weight path ending at any element of last row in a matrix
C#
1196
Chapter 170. Maximum weight path ending at any element of last row in a matrix
// row in a matrix
using System;
class GFG {
/* Function which return the
maximum weight path sum */
public static int maxCost(int [,] mat, int N)
{
// create 2D matrix to store the
// sum of the path
int [,] dp = new int[N,N];
dp[0,0] = mat[0,0];
// Initialize first column of total
// weight array (dp[i to N][0])
for (int i = 1; i < N; i++)
dp[i,0] = mat[i,0] + dp[i-1,0];
// Calculate rest path sum of weight matrix
for (int i = 1; i < N; i++)
for (int j = 1; j < i + 1 && j < N; j++)
dp[i,j] = mat[i,j] +
Math.Max(dp[i-1,j-1], dp[i-1,j]);
// find the max weight path sum to reach
// the last row
int result = 0;
for (int i = 0; i < N; i++)
if (result < dp[N-1,i])
result = dp[N-1,i];
// return maximum weight path sum
return result;
}
/* Driver program to test above function */
public static void Main()
{
int [,] mat = { { 4, 1 ,5 ,6 , 1 },
{ 2 ,9 ,2 ,11 ,10 },
{ 15,1 ,3 ,15, 2 },
{ 16, 92, 41,4,3},
{ 8, 142, 6, 4, 8 }
};
1197
Chapter 170. Maximum weight path ending at any element of last row in a matrix
int N = 5;
Console.Write("Maximum Path Sum : "
+ maxCost(mat, N));
}
}
// This code is contributed by KRV.
Output:
Source
https://www.geeksforgeeks.org/maximum-weight-path-ending-element-last-row-matrix/
1198
Chapter 171
Input : 1 2 3
4 5 6
7 8 9
Output :Mean: 5
Median: 5
Input : 1 1 1
2 2 2
4 4 4
Output :Mean: 2
Median: 2
Mean of matrix is =
(sum of all elements of matrix)/
(total elements of matrix)
Note that this definition doesn't require
matrix to be sorted and works for all
matrices.
1199
Chapter 171. Mean and Median of a matrix
If given matrix is unsorted, we can find its median by first sorting the matrix.
C++
1200
Chapter 171. Mean and Median of a matrix
Java
1201
Chapter 171. Mean and Median of a matrix
C#
1202
Chapter 171. Mean and Median of a matrix
a[ N / 2, 0] ) / (2.0);
return 0;
}
// Driver Code
public static void Main ()
{
int [,]a= { { 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16} };
int n = a.GetLength(0);
Console.WriteLine("Mean : " +
findMean(a, n));
Console.WriteLine("Median : " +
findMedian(a, n));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to find
// mean and median
// of sorted square
// matrix.
$N = 4;
// Returns mean of
// a given matrix of
// size n x n.
function findMean($a)
{
global $N;
$sum = 0;
// total sum calculation
// of matrix
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
1203
Chapter 171. Mean and Median of a matrix
$sum += $a[$i][$j];
return (double)$sum / ($N * $N);
}
// Function for calculating median
function findMedian($a)
{
global $N;
if ($N % 2 != 0)
return $a[$N / 2][$N / 2];
if ($N % 2 == 0)
return ($a[($N - 2) / 2][$N - 1] +
$a[$N / 2][0]) / 2.0;
}
// Driver Code
$a= array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 10, 11, 12),
array(13, 14, 15, 16));
echo "Mean : " , findMean($a),"\n",
"Median : ", findMedian($a);
// This code is contributed by vt_m.
?>
Output:
Mean : 8.5
Median : 8.5
Source
https://www.geeksforgeeks.org/mean-median-matrix/
1204
Chapter 172
The path with minimum cost is highlighted in the following figure. The path is (0, 0) –>
(0, 1) –> (1, 2) –> (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).
1205
Chapter 172. Min Cost Path | DP-6
1) Optimal Substructure
The path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or
(m, n-1). So minimum cost to reach (m, n) can be written as “minimum of the 3 cells plus
cost[m][n]”.
minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]
2) Overlapping Subproblems
Following is simple recursive implementation of the MCP (Minimum Cost Path) problem.
The implementation simply follows the recursive structure mentioned above.
1206
Chapter 172. Min Cost Path | DP-6
{1, 5, 3} };
printf(" %d ", minCost(cost, 2, 2));
return 0;
}
Java
1207
Chapter 172. Min Cost Path | DP-6
// This code is contributed by Sam007
Python3
C#
1208
Chapter 172. Min Cost Path | DP-6
PHP
<?php
/* A Naive recursive implementation
of MCP(Minimum Cost Path) problem */
1209
Chapter 172. Min Cost Path | DP-6
$R = 3;
$C = 3;
/* Returns cost of minimum
cost path from (0,0) to
(m, n) in mat[R][C]*/
function minCost($cost, $m, $n)
{
global $R;
global $C;
if ($n < 0 || $m < 0)
return PHP_INT_MAX;
else if ($m == 0 && $n == 0)
return $cost[$m][$n];
else
return $cost[$m][$n] +
min1(minCost($cost, $m - 1, $n - 1),
minCost($cost, $m - 1, $n),
minCost($cost, $m, $n - 1) );
}
/* A utility function that
returns minimum of 3 integers */
function min1($x, $y, $z)
{
if ($x < $y)
return ($x < $z)? $x : $z;
else
return ($y < $z)? $y : $z;
}
// Driver Code
$cost = array(array(1, 2, 3),
array (4, 8, 2),
array (1, 5, 3));
echo minCost($cost, 2, 2);
// This code is contributed by mits.
?>
Output:
It should be noted that the above function computes the same subproblems again and again.
1210
Chapter 172. Min Cost Path | DP-6
See the following recursion tree, there are many nodes which apear more than once. Time
complexity of this naive recursive solution is exponential and it is terribly slow.
mC refers to minCost()
mC(2, 2)
/ | \
/ | \
mC(1, 1) mC(1, 2) mC(2, 1)
/ | \ / | \ / | \
/ | \ / | \ / | \
mC(0,0) mC(0,1) mC(1,0) mC(0,1) mC(0,2) mC(1,1) mC(1,0) mC(1,1) mC(2,0)
So the MCP problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by constructing a temporary array tc[][] in bottom up manner.
C++
1211
Chapter 172. Min Cost Path | DP-6
Java
1212
Chapter 172. Min Cost Path | DP-6
tc[0][0] = cost[0][0];
/* Initialize first column of total cost(tc) array */
for (i = 1; i <= m; i++)
tc[i][0] = tc[i-1][0] + cost[i][0];
/* Initialize first row of tc array */
for (j = 1; j <= n; j++)
tc[0][j] = tc[0][j-1] + cost[0][j];
/* Construct rest of the tc array */
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
tc[i][j] = min(tc[i-1][j-1],
tc[i-1][j],
tc[i][j-1]) + cost[i][j];
return tc[m][n];
}
/* Driver program to test above functions */
public static void main(String args[])
{
int cost[][]= {{1, 2, 3},
{4, 8, 2},
{1, 5, 3}};
System.out.println(minCost(cost,2,2));
}
}
// This code is contributed by Pankaj Kumar
Python
1213
Chapter 172. Min Cost Path | DP-6
# Initialize first column of total cost(tc) array
for i in range(1, m+1):
tc[i][0] = tc[i-1][0] + cost[i][0]
# Initialize first row of tc array
for j in range(1, n+1):
tc[0][j] = tc[0][j-1] + cost[0][j]
# Construct rest of the tc array
for i in range(1, m+1):
for j in range(1, n+1):
tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]
return tc[m][n]
# Driver program to test above functions
cost = [[1, 2, 3],
[4, 8, 2],
[1, 5, 3]]
print(minCost(cost, 2, 2))
# This code is contributed by Bhavya Jain
C#
1214
Chapter 172. Min Cost Path | DP-6
/* Initialize first column of total cost(tc) array */
for (i = 1; i <= m; i++)
tc[i, 0] = tc[i - 1, 0] + cost[i, 0];
/* Initialize first row of tc array */
for (j = 1; j <= n; j++)
tc[0, j] = tc[0, j - 1] + cost[0, j];
/* Construct rest of the tc array */
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
tc[i, j] = min(tc[i - 1, j - 1],
tc[i - 1, j],
tc[i, j - 1]) + cost[i, j];
return tc[m, n];
}
// Driver program
public static void Main()
{
int [,]cost= {{1, 2, 3},
{4, 8, 2},
{1, 5, 3}};
Console.Write(minCost(cost,2,2));
}
}
// This code is contributed by Sam007.
PHP
<?php
// DP implementation
// of MCP problem
$R = 3;
$C = 3;
function minCost($cost, $m, $n)
{
global $R;
global $C;
// Instead of following line,
// we can use int tc[m+1][n+1]
// or dynamically allocate
// memory to save space. The
// following line is used to keep
1215
Chapter 172. Min Cost Path | DP-6
Output:
1216
Chapter 172. Min Cost Path | DP-6
Time Complexity of the DP implementation is O(mn) which is much better than Naive
Recursive implementation.
Improved By : Sam007, Mithun Kumar, shiv_bhakt, maveriek
Source
https://www.geeksforgeeks.org/min-cost-path-dp-6/
1217
Chapter 173
Minimum Cost Path with Left, Right, Bottom and Up moves allowed - GeeksforGeeks
Given a two dimensional grid, each cell of which contains integer cost which represents a
cost to traverse through that cell, we need to find a path from top left cell to bottom right
cell by which total cost incurred is minimum.
Note : It is assumed that negative cost cycles do not exist in input matrix.
This problem is extension of below problem.
Min Cost Path with right and bottom moves allowed.
In previous problem only going right and bottom was allowed but in this problem we are
allowed to go bottom, up, right and left i.e. in all 4 direction.
Examples:
It is not possible to solve this problem using dynamic programming similar to previous
problem because here current state depends not only on right and bottom cells but also on
1218
Chapter 173. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
left and upper cells. We solve this problem using dijkstra’s algorithm. Each cell of grid
represents a vertex and neighbor cells adjacent vertices. We do not make an explicit graph
from these cells instead we will use matrix as it is in our dijkstra’s algorithm.
In below code Dijkstra’ algorithm’s implementation using C++ STL is used. The code
implemented below is changed to cope with matrix represented implicit graph. Please also
see use of dx and dy arrays in below code, these arrays are taken for simplifying the process
of visiting neighbor vertices of each cell.
1219
Chapter 173. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
{
int dis[row][col];
// initializing distance array by INT_MAX
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
dis[i][j] = INT_MAX;
// direction arrays for simplification of getting
// neighbour
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
set<cell> st;
// insert (0, 0) cell with 0 distance
st.insert(cell(0, 0, 0));
// initialize distance of (0, 0) with its grid value
dis[0][0] = grid[0][0];
// loop for standard dijkstra's algorithm
while (!st.empty())
{
// get the cell with minimum distance and delete
// it from the set
cell k = *st.begin();
st.erase(st.begin());
// looping through all neighbours
for (int i = 0; i < 4; i++)
{
int x = k.x + dx[i];
int y = k.y + dy[i];
// if not inside boundry, ignore them
if (!isInsideGrid(x, y))
continue;
// If distance from current cell is smaller, then
// update distance of neighbour cell
if (dis[x][y] > dis[k.x][k.y] + grid[x][y])
{
// If cell is already there in set, then
// remove its previous entry
if (dis[x][y] != INT_MAX)
st.erase(st.find(cell(x, y, dis[x][y])));
1220
Chapter 173. Minimum Cost Path with Left, Right, Bottom and Up moves allowed
Output:
327
Source
https://www.geeksforgeeks.org/minimum-cost-path-left-right-bottom-moves-allowed/
1221
Chapter 174
1222
Chapter 174. Minimum Initial Points to Reach Destination
At the first look, this problem looks similar Max/Min Cost Path, but maximum overall
points gained will not guarantee the minimum initial points. Also, it is compulsory in
the current problem that the points never drops to zero or below. For instance, Suppose
following two paths exists from source to destination cell.
We can solve this problem through bottom-up table filling dynamic programing technique.
• To begin with, we should maintain a 2D array dp of the same size as the grid, where
dp[i][j] represents the minimum points that guarantees the continuation of the journey
to destination before entering the cell (i, j). It’s but obvious that dp[0][0] is our final
solution. Hence, for this problem, we need to fill the table from the bottom right
corner to left top.
• Now, let us decide minimum points needed to leave cell (i, j) (remember we are
moving from bottom to up). There are only two paths to choose: (i+1, j) and (i,
j+1). Of course we will choose the cell that the player can finish the rest of his
journey with a smaller initial points. Therefore we have: min_Points_on_exit =
min(dp[i+1][j], dp[i][j+1])
Now we know how to compute min_Points_on_exit, but we need to fill the table dp[][] to
get the solution in dp[0][0].
How to compute dp[i][j]?
The value of dp[i][j] can be written as below.
• If points[i][j] == 0, then nothing is gained in this cell; the player can leave the cell
with the same points as he enters the room with, i.e. dp[i][j] = min_Points_on_exit.
• If dp[i][j] < 0, then the player must have points greater than min_Points_on_exit be-
fore entering (i, j) in order to compensate for the points lost in this cell. The minimum
amount of compensation is ” – points[i][j] ”, so we have dp[i][j] = min_Points_on_exit
– points[i][j].
• If dp[i][j] > 0, then the player could enter (i, j) with points as little as
min_Points_on_exit – points[i][j]. since he could gain “points[i][j]” points in
this cell. However, the value of min_Points_on_exit – points[i][j] might drop to 0 or
below in this situation. When this happens, we must clip the value to 1 in order to
make sure dp[i][j] stays positive:
dp[i][j] = max(min_Points_on_exit – points[i][j], 1).
C++
1223
Chapter 174. Minimum Initial Points to Reach Destination
1224
Chapter 174. Minimum Initial Points to Reach Destination
<< minInitialPoints(points);
return 0;
}
Java
class min_steps
{
static int minInitialPoints(int points[][],int R,int C)
{
// dp[i][j] represents the minimum initial points player
// should have so that when starts with cell(i, j) successfully
// reaches the destination cell(m-1, n-1)
int dp[][] = new int[R][C];
int m = R, n = C;
// Base case
dp[m-1][n-1] = points[m-1][n-1] > 0? 1:
Math.abs(points[m-1][n-1]) + 1;
// Fill last row and last column as base to fill
// entire table
for (int i = m-2; i >= 0; i--)
dp[i][n-1] = Math.max(dp[i+1][n-1] - points[i][n-1], 1);
for (int j = n-2; j >= 0; j--)
dp[m-1][j] = Math.max(dp[m-1][j+1] - points[m-1][j], 1);
// fill the table in bottom-up fashion
for (int i=m-2; i>=0; i--)
{
for (int j=n-2; j>=0; j--)
{
int min_points_on_exit = Math.min(dp[i+1][j], dp[i][j+1]);
dp[i][j] = Math.max(min_points_on_exit - points[i][j], 1);
}
}
return dp[0][0];
}
/* Driver program to test above function */
public static void main (String args[])
{
int points[][] = { {-2,-3,3},
{-5,-10,1},
{10,30,-5}
};
int R = 3,C = 3;
1225
Chapter 174. Minimum Initial Points to Reach Destination
C#
1226
Chapter 174. Minimum Initial Points to Reach Destination
dp[i, j] = Math.Max(min_points_on_exit -
points[i, j], 1);
}
}
return dp[0, 0];
}
// Driver Code
public static void Main ()
{
int [,]points = {{-2,-3,3},
{-5,-10,1},
{10,30,-5}};
int R = 3,C = 3;
Console.Write("Minimum Initial Points Required: "+
minInitialPoints(points, R, C));
}
}
// This code is contributed by nitin mittal.
Output:
This article is contributed by Gaurav Ahirwar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal, PrathamKohli
Source
https://www.geeksforgeeks.org/minimum-positive-points-to-reach-destination/
1227
Chapter 175
Minimum cells required to reach destination with jumps equal to cell values - GeeksforGeeks
Given a m x n matrix mat[][] containing positive integers. The problem is to reach to the
cell (m-1, n-1) from the cell (0, 0) by following the given constraints. From a cell (i, j) one
can move ‘exactly’ a distance of ‘mat[i][j]’ to the right (in the same row) or to below (in the
same column) only if the movement takes to a cell within matrix boundaries.
For example: Given mat[1][1] = 4, then one can move to cells mat[1][5] and mat[5][1] only if
these cells exists in the matrix. Following the constraints check whether one can reach cell
(m-1, n-1) from (0, 0). 1If one can reach then print the minimum number of cells required
to be covered during the movement else print “-1”.
Examples:
1228
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
C++
1229
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
Java
1230
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
1231
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
C#
1232
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
1233
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
PHP
<?php
// PHP implementation to count
// minimum cells required to be
// covered to reach destination
// function to count minimum
// cells required to be
// covered to reach destination
function minCells( $mat, $m, $n)
{
// to store min cells
// required to be
// covered to reach
// a particular cell
$dp =array(array());
// initially no cells
// can be reached
for($i = 0; $i < $m; $i++)
for($j = 0; $j < $n; $j++)
$dp[$i][$j] = PHP_INT_MAX;
// base case
$dp[0][0] = 1;
// building up the dp[][] matrix
for($i = 0; $i < $m; $i++)
{
for($j = 0; $j < $n; $j++)
{
// dp[i][j] != INT_MAX
// denotes that cell (i, j)
// can be reached from cell
// (0, 0) and the other half
// of the condition finds the
// cell on the right that can
// be reached from (i, j)
if ($dp[$i][$j] != PHP_INT_MAX and
1234
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
Output:
1235
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values
Source
https://www.geeksforgeeks.org/minimum-cells-required-reach-destination-jumps-equal-cell-values/
1236
Chapter 176
Minimum cells traversed to reach corner where every cell represents jumps - GeeksforGeeks
Suppose A is at position (0, 0) of a 2-D grid containing ‘m’ rows and ‘n’ columns. His aim is
to reach the bottom right point of this grid traveling through as minimum number of cells
as possible.
Each cell of the grid contains a positive integer that defines the number of cells A can jump
either in the right or the downward direction when he reaches that cell.
Find the minimum no of cells that need to be touched in order to reach bottom right corner.
Examples:
Input : 2 4 2
5 3 8
1 1 1
Output :
So following two paths exist to reach (2, 2) from (0, 0)
(0, 0) => (0, 2) => (2, 2)
(0, 0) => (2, 0) => (2, 1) => (2, 2)
1. Think of this matrix as tree and (0, 0) as root and apply BFS using level order
traversal.
1237
Chapter 176. Minimum cells traversed to reach corner where every cell represents jumps
1238
Chapter 176. Minimum cells traversed to reach corner where every cell represents jumps
// when destination cannot be reached
return -1;
}
// driver function
int main()
{
int M[R][C] = { { 2, 4, 2 },
{ 5, 3, 8 },
{ 1, 1, 1 } };
cout << matrixJump(M, 0, 0);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-cells-traversed-reach-corner-every-cell-represents-jumps/
1239
Chapter 177
Input : 8 5 6
3 8 7
4 9 2
Output : 2
5 in row 1 col 2 should be changed to 1
8 in row 2 col 2 should be changed to 5
Total 2 changes are required.
Input : 8 9 4
5 9 3
6 1 8
Output : 3
8 in row 1 col 1 should be changed to 2
5 in row 2 col 1 should be changed to 7
9 in row 2 col 2 should be changed to 5
Total 3 changes are required.
1240
Chapter 177. Minimum changes needed to make a 3*3 matrix magic square
816
357
492
618
753
294
492
357
816
294
753
618
834
159
672
438
951
276
672
159
834
276
951
438
We create a 3D array to store these 8 matrices. Now we check the input matrix for each
of these 8 matrices and find out the one which can be obtained with the least number of
changes.
class GfG {
// this program takes in two 2D arrays as
// input and compares them to find out the
// minimum number of changes that needs to
// be made to convert arr to ms.
public static int findMinimumFromMS(int[][] arr,
int[][] ms)
{
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (arr[i][j] != ms[i][j])
count++;
}
}
1241
Chapter 177. Minimum changes needed to make a 3*3 matrix magic square
return count;
}
public static int findMinimum(int[][] arr)
{
int[][][] ms = {
{ { 8, 1, 6 }, { 3, 5, 7 }, { 4, 9, 2 } },
{ { 6, 1, 8 }, { 7, 5, 3 }, { 2, 9, 4 } },
{ { 4, 9, 2 }, { 3, 5, 7 }, { 8, 1, 6 } },
{ { 2, 9, 4 }, { 7, 5, 3 }, { 6, 1, 8 } },
{ { 8, 3, 4 }, { 1, 5, 9 }, { 6, 7, 2 } },
{ { 4, 3, 8 }, { 9, 5, 1 }, { 2, 7, 6 } },
{ { 6, 7, 2 }, { 1, 5, 9 }, { 8, 3, 4 } },
{ { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } },
};
// If all the elements need to be changed,
// there would be 9 changes, so we take the
// max as 9
int min = 9;
for (int i = 0; i < 8; i++) {
int x = findMinimumFromMS(arr, ms[i]);
if (x < min)
min = x;
}
return min;
}
public static void main(String[] args)
{
int[][] arr = { { 8, 5, 6 }, { 3, 8, 7 },
{ 4, 9, 2 } };
System.out.println(findMinimum(arr));
}
}
Output:
Source
https://www.geeksforgeeks.org/minimum-changes-needed-to-make-a-33-matrix-magic-square/
1242
Chapter 178
Input : mat[][] = { { 4, 9, 2 },
{ 3, 5, 7 },
{ 8, 1, 5 }};
Output : 1
Given matrix s is not a magic square. To convert
it into magic square we change the bottom right
value, s[2][2], from 5 to 6 at a cost of | 5 - 6 |
= 1.
Input : mat[][] = { { 4, 8, 2 },
{ 4, 5, 7 },
{ 6, 1, 6 }};
Output : 4
The idea is to find all 3 X 3 magic squares and, for each one, compute the cost of changing
mat into a known magic square. The result is the smallest of these costs.
We know that s will always be 3 X 3. There are 8 possible magic squares for 3 X 3 matrix.
1243
Chapter 178. Minimum cost to convert 3 X 3 matrix into magic square
#include <bits/stdc++.h>
using namespace std;
// Return if given vector denote the magic square or not.
bool is_magic_square(vector<int> v)
{
int a[3][3];
// Convert vector into 3 X 3 matrix
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
a[i][j] = v[3 * i + j];
int s = 0;
for (int j = 0; j < 3; ++j)
s += a[0][j];
// Checking if each row sum is same
for (int i = 1; i <= 2; ++i) {
int tmp = 0;
for (int j = 0; j < 3; ++j)
tmp += a[i][j];
if (tmp != s)
return 0;
}
// Checking if each column sum is same
for (int j = 0; j < 3; ++j) {
int tmp = 0;
for (int i = 0; i < 3; ++i)
tmp += a[i][j];
if (tmp != s)
return 0;
}
// Checking if diagonal 1 sum is same
int tmp = 0;
for (int i = 0; i < 3; ++i)
tmp += a[i][i];
if (tmp != s)
return 0;
1244
Chapter 178. Minimum cost to convert 3 X 3 matrix into magic square
1245
Chapter 178. Minimum cost to convert 3 X 3 matrix into magic square
// Finding the difference with each magic square
// and assigning the minimum value.
res = min(res, diff(v, magic_squares[i]));
}
return res;
}
// Driven Program
int main()
{
// Taking matrix in vector in rowise to make
// calculation easy
vector<int> v;
v.push_back(4);
v.push_back(9);
v.push_back(2);
v.push_back(3);
v.push_back(5);
v.push_back(7);
v.push_back(8);
v.push_back(1);
v.push_back(5);
cout << wrapper(v) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-convert-3-x-3-matrix-magic-square/
1246
Chapter 179
1247
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
Algorithm:
calculateEnergy(mat, n)
Declare i_des, j_des, q
Initialize tot_energy = 0
for i = 0 to n-1
for j = 0 to n-1
q = mat[i][j] / n
i_des = q
j_des = mat[i][j] - (n * q)
tot_energy += abs(i_des - i) + abs(j_des - j)
return tot_energy
C++
1248
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
q = mat[i][j] / n;
// final destination location (i_des, j_des) of
// the element mat[i][j] is being calculated
i_des = q;
j_des = mat[i][j] - (n * q);
// energy required for the moevement of the
// element mat[i][j] is calculated and then
// accumulated in the 'tot_energy'
tot_energy += abs(i_des - i) + abs(j_des - j);
}
}
// required total energy
return tot_energy;
}
// Driver program to test above
int main()
{
int mat[SIZE][SIZE] = { { 4, 7, 0, 3 },
{ 8, 5, 6, 1 },
{ 9, 11, 10, 2 },
{ 15, 13, 14, 12 } };
int n = 4;
cout << "Total energy required = "
<< calculateEnergy(mat, n) << " units";
return 0;
}
Java
1249
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
1250
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
}
}
// This code is contributed by Sagar Shukla
Python3
1251
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
C#
// C# implementation to find
// the total energy required
// to rearrange the numbers
using System;
class GFG {
// function to find the total energy
// required to rearrange the numbers
public static int calculateEnergy(int[, ] mat,
int n)
{
int i_des, j_des, q;
int tot_energy = 0;
// nested loops to acess the elements
// of the given matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// store quotient
q = mat[i, j] / n;
// final destination location
// (i_des, j_des) of
// the element mat[i][j] is
// being calculated
i_des = q;
j_des = mat[i, j] - (n * q);
// energy required for the
// movement of the
// element mat[i][j] is
// calculated and then
// accumulated in the 'tot_energy'
tot_energy += Math.Abs(i_des - i) +
Math.Abs(j_des - j);
}
1252
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
}
// required total energy
return tot_energy;
}
// Driver function
public static void Main()
{
int[, ] mat = new int[, ]{ { 4, 7, 0, 3 },
{ 8, 5, 6, 1 },
{ 9, 11, 10, 2 },
{ 15, 13, 14, 12 } };
int n = 4;
Console.Write("Total energy required = " +
calculateEnergy(mat, n) + " units");
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP implementation to find
// the total energy required
// to rearrange the numbers
// function to find the total energy
// required to rearrange the numbers
function calculateEnergy($mat, $n)
{
$i_des; $j_des; $q;
$tot_energy = 0;
// nested loops to acess the
// elements of the given matrix
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// store quotient
$q = (int)($mat[$i][$j] / $n);
// final destination location
1253
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1
Output :
Source
https://www.geeksforgeeks.org/minimum-cost-sort-matrix-numbers-0-n2-1/
1254
Chapter 180
Minimum difference between adjacent elements of array which contain elements from each
row of a matrix - GeeksforGeeks
Given a matrix of N rows and M columns, the task is to find the minimum absolute
difference between any of the two adjacent elements of an array of size N, which is created
by picking one element from each row of the matrix. Note the element picked from row 1
will become arr[0], element picked from row 2 will become arr[1] and so on.
Examples:
Input : N = 2, M = 2
m[2][2] = { 8, 2,
6, 8 }
Output : 0.
Picking 8 from row 1 and picking 8 from row 2, we create an array { 8, 8 } and minimum
difference between any of adjacent element is 0.
Input : N = 3, M = 3
m[3][3] = { 1, 2, 3
4, 5, 6
7, 8, 9 }
Output : 1.
The idea is to sort all rows individually and then do binary search to find the closest element
in next row for each element.
1255
Chapter 180. Minimum difference between adjacent elements of array which contain
elements from each row of a matrix
To do this in an efficient manner, sort each row of the matrix. Starting from row 1 to row N
– 1 of matrix, for each element m[i][j] of current row in the matrix, find the smallest element
in the next row which is greater than or equal to the current element, say p and the largest
element which is smaller than the current element, say q. This can be done using Binary
Search. Finally,find the minimum of the difference of current element from p and q and
update the variable.
Below is implementation of this approach:
C/C++
1256
Chapter 180. Minimum difference between adjacent elements of array which contain
elements from each row of a matrix
{
for (int j = 0; j < m; j++)
{
// Search smallest element in the next row which
// is greater than or equal to the current element
int p = bsearch(0, m-1, arr[i][j], arr[i + 1]);
ans = min(ans, abs(arr[i + 1][p] - arr[i][j]));
// largest element which is smaller than the current
// element in the next row must be just before
// smallest element which is greater than or equal
// to the current element because rows are sorted.
if (p-1 >= 0)
ans = min(ans, abs(arr[i + 1][p - 1] - arr[i][j]));
}
}
return ans;
}
// Driven Program
int main()
{
int m[R][C] =
{
8, 5,
6, 8,
};
cout << mindiff(m, R, C) << endl;
return 0;
}
Java
1257
Chapter 180. Minimum difference between adjacent elements of array which contain
elements from each row of a matrix
{
int mid = (low + high)/2;
if(low <= high)
{
if(arr[mid] < n)
return bsearch(mid +1, high, n, arr);
return bsearch(low, mid - 1, n, arr);
}
return low;
}
// Return the minimum absolute difference adjacent
// elements of array
static int mindiff(int arr[][], int n, int m)
{
// Sort each row of the matrix.
for (int i = 0; i < n; i++)
Arrays.sort(arr[i]);
int ans = +2147483647;
// For each matrix element
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < m; j++)
{
// Search smallest element in the
// next row which is greater than
// or equal to the current element
int p = bsearch(0, m-1, arr[i][j], arr[i + 1]);
ans = Math.min(ans, Math.abs(arr[i + 1][p] - arr[i][j]));
// largest element which is smaller than the current
// element in the next row must be just before
// smallest element which is greater than or equal
// to the current element because rows are sorted.
if (p-1 >= 0)
ans = Math.min(ans,
Math.abs(arr[i + 1][p - 1] - arr[i][j]));
}
}
return ans;
}
1258
Chapter 180. Minimum difference between adjacent elements of array which contain
elements from each row of a matrix
//Driver code
public static void main (String[] args)
{
int m[][] ={{8, 5},
{6, 8}};
System.out.println(mindiff(m, R, C));
}
}
//This code is contributed by Anant Agarwal.
Python
1259
Chapter 180. Minimum difference between adjacent elements of array which contain
elements from each row of a matrix
Output:
Source
https://www.geeksforgeeks.org/minimum-difference-adjacent-elements-array-contain-elements-row-matrix/
1260
Chapter 181
Input : mat[][] = { { 0, 0, 1 },
{ 1, 1, 1 },
{ 1, 0, 0 } };
Output : 2
Value of mat[1][0] is not equal to mat[0][1].
Value of mat[2][1] is not equal to mat[1][2].
So, two flip are required.
Input : mat[][] = { { 1, 1, 1, 1, 0 },
{ 0, 1, 0, 1, 1 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 0, 0, 1 } };
Output : 3
Method 1 (Simple):
The idea is to find the transpose of the matrix and find minimum number of flip required
to make transpose and original matrix equal. To find minimum flip, find the number of
position where original matrix and transpose matrix are not same, say x. So, our answer
will be x/2.
Below is the implementation of this approach:
1261
Chapter 181. Minimum flip required to make Binary Matrix symmetric
C++
Java
1262
Chapter 181. Minimum flip required to make Binary Matrix symmetric
Python3
1263
Chapter 181. Minimum flip required to make Binary Matrix symmetric
# Return the minimum flip required
# to make Binary Matrix symmetric
# along main diagonal.
def minimumflip(mat, n):
transpose =[[0] * n] * n
# finding the transpose of the matrix
for i in range(n):
for j in range(n):
transpose[i][j] = mat[j][i]
# Finding the number of position
# where element are not same.
flip = 0
for i in range(n):
for j in range(n):
if transpose[i][j] != mat[i][j]:
flip += 1
return int(flip / 2)
# Driver Program
n = 3
mat =[[ 0, 0, 1],
[ 1, 1, 1],
[ 1, 0, 0]]
print( minimumflip(mat, n))
# This code is contributed by "Sharad_Bhardwaj".
C#
1264
Chapter 181. Minimum flip required to make Binary Matrix symmetric
PHP
<?php
// PHP Program to find minimum
// flip required to make
$N = 3;
// Return the minimum flip
// required to make Binary
// Matrix symmetric along
// main diagonal.
function minimumflip($mat, $n)
{
global $N;
$transpose;
// finding the transpose
// of the matrix
1265
Chapter 181. Minimum flip required to make Binary Matrix symmetric
Output :
C++
1266
Chapter 181. Minimum flip required to make Binary Matrix symmetric
Java
1267
Chapter 181. Minimum flip required to make Binary Matrix symmetric
return flip;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int n = 3;
int mat[][] = {{ 0, 0, 1 },
{ 1, 1, 1 },
{ 1, 0, 0 }};
System.out.println(minimumflip(mat, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
1268
Chapter 181. Minimum flip required to make Binary Matrix symmetric
PHP
<?php
// PHP Program to find minimum
// flip required to make Binary
// Matrix symmetric along main diagonal
$N = 3;
// Return the minimum flip
// required to make Binary
// Matrix symmetric along main diagonal.
1269
Chapter 181. Minimum flip required to make Binary Matrix symmetric
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/minimum-flip-required-make-binary-matrix-symmetric/
1270
Chapter 182
1271
Chapter 182. Minimum jumps to reach last building in a matrix
# define R 4
# define C 3
bool isSafe(int x, int y)
{
return (x < R && y < C);
}
/* Returns minimum jump path from (0, 0) to
(m, n) in hight[R][C]*/
int minJump(int height[R][C], int x, int y)
{
// base case
if (x == R - 1 && y == C - 1)
return 0;
// Find minimum jumps if we go through diagonal
int diag = INT_MAX;
if (isSafe(x + 1, y + 1))
diag = minJump(height, x + 1, y + 1) +
abs(height[x][y] - height[x + 1][y + 1]);
// Find minimum jumps if we go through down
int down = INT_MAX;
if (isSafe(x + 1, y))
down = minJump(height, x + 1, y) +
abs(height[x][y] - height[x + 1][y]);
// Find minimum jumps if we go through right
int right = INT_MAX;
if (isSafe(x, y + 1))
right = minJump(height, x, y + 1) +
abs(height[x][y] - height[x][y + 1]);
// return minimum jumps
return min({down, right, diag});
}
/* Driver program to test above functions */
int main()
{
int height[][C] = { { 5, 4, 2 },
{ 9, 2, 1 },
{ 2, 5, 9 },
{ 1, 3, 11 } };
cout << minJump(height, 0, 0);
return 0;
1272
Chapter 182. Minimum jumps to reach last building in a matrix
Java
1273
Chapter 182. Minimum jumps to reach last building in a matrix
right = minJump(height, x, y + 1) +
Math.abs(height[x][y] - height[x][y + 1]);
// return minimum jumps
return Math.min(down, Math.min(right, diag));
}
// Driver program
public static void main(String[] args)
{
int height[][] = { { 5, 4, 2 },
{ 9, 2, 1 },
{ 2, 5, 9 },
{ 1, 3, 11} };
System.out.println(minJump(height, 0, 0));
}
}
// This article is contributed by Prerna Saini.
C#
// Recursive C# program
// to find minimum jumps
// to reach last building
// from first.
using System;
class GFG {
static bool isSafe(int x, int y)
{
return (x < 4 && y < 3);
}
// Returns minimum jump
// path from (0, 0) to
// (m, n) in hight[R][C]
static int minJump(int [,]height,
int x, int y)
{
// base case
if (x == 4 - 1 && y == 3 - 1)
return 0;
// Find minimum jumps
1274
Chapter 182. Minimum jumps to reach last building in a matrix
// if we go through
// diagonal
int diag = int.MaxValue;
if (isSafe(x + 1, y + 1))
diag = minJump(height, x + 1, y + 1) +
Math.Abs(height[x,y] -
height[x + 1,y + 1]);
// Find minimum jumps
// if we go through
// down
int down = int.MaxValue;
if (isSafe(x + 1, y))
down = minJump(height, x + 1, y) +
Math.Abs(height[x,y] -
height[x + 1,y]);
// Find minimum jumps
// if we go through right
int right = int.MaxValue;
if (isSafe(x, y + 1))
right = minJump(height, x, y + 1) +
Math.Abs(height[x,y] -
height[x,y + 1]);
// return minimum jumps
return Math.Min(down, Math.Min(right, diag));
}
// Driver code
public static void Main()
{
int [,]height = {{5, 4, 2},
{9, 2, 1},
{2, 5, 9},
{1, 3, 11}};
Console.Write(minJump(height, 0, 0));
}
}
// This code is contributed by nitin mittal
PHP
1275
Chapter 182. Minimum jumps to reach last building in a matrix
<?php
// Recursive PHP program to
// find minimum jumps to
// reach last building from first.
$R = 4;
$C = 3;
function isSafe($x, $y)
{
global $R, $C;
return ($x < $R and $y < $C);
}
// Returns minimum jump
// path from (0, 0) to
// (m, n) in hight[R][C]
function minJump($height, $x, $y)
{
global $R, $C;
// base case
if ($x == $R - 1 and $y == $C - 1)
return 0;
// Find minimum jumps if
// we go through diagonal
$diag = PHP_INT_MAX;
if (isSafe($x + 1, $y + 1))
$diag = minJump($height, $x + 1, $y + 1) +
abs($height[$x][$y] -
$height[$x + 1][$y + 1]);
// Find minimum jumps
// if we go through down
$down = PHP_INT_MAX;
if (isSafe($x + 1, $y))
$down = minJump($height, $x + 1, $y) +
abs($height[$x][$y] -
$height[$x + 1][$y]);
// Find minimum jumps if
// we go through right
$right = PHP_INT_MAX;
if (isSafe($x, $y + 1))
$right = minJump($height, $x, $y + 1) +
abs($height[$x][$y] -
$height[$x][$y + 1]);
1276
Chapter 182. Minimum jumps to reach last building in a matrix
// return minimum jumps
return min($down, min($right, $diag));
}
// Driver Code
$height = array(array( 5, 4, 2 ),
array( 9, 2, 1 ),
array( 2, 5, 9 ),
array( 1, 3, 11 ));
echo minJump($height, 0, 0);
// This code is contributed by anuj_67.
?>
Output :
12
1277
Chapter 182. Minimum jumps to reach last building in a matrix
Output:
12
1278
Chapter 182. Minimum jumps to reach last building in a matrix
Source
https://www.geeksforgeeks.org/minimum-jumps-to-reach-last-building-in-a-matrix/
1279
Chapter 183
Minimum operations required to make each row and column of matrix equals - Geeks-
forGeeks
Given a square matrix of size . Find minimum number of operation are required
such that sum of elements on each row and column becomes equals. In one operation,
increment any value of cell of matrix by 1. In first line print minimum operation required
and in next ‘n’ lines print ‘n’ integers representing the final matrix after operation.
Input:
1 2
3 4
Output:
4
4 3
3 4
Explanation
1. Increment value of cell(0, 0) by 3
2. Increment value of cell(0, 1) by 1
Hence total 4 operation are required
Input: 9
1 2 3
4 2 3
3 2 1
Output:
6
1280
Chapter 183. Minimum operations required to make each row and column of matrix equals
2 4 3
4 2 3
3 3 3
The approach is simple, let’s assume that maxSum is the maximum sum among all rows
and columns. We just need to increment some cells such that the sum of any row or column
becomes ‘maxSum’.
Let’s say Xi is the total number of operation needed to make the sum on row ‘i’ equals to
maxSum and Yj is the total number of operation needed to make the sum on column ‘j’
equals to maxSum. Since Xi = Yj so we need to work at any one of them according to the
condition.
In order to minimise Xi , we need to choose the maximum from rowSumi and colSumj as
it will surely lead to minimum operation. After that, increment ‘i’ or ‘j’ according to the
condition satisfied after increment.
Below is the implementation of the above approach.
C++
1281
Chapter 183. Minimum operations required to make each row and column of matrix equals
}
int count = 0;
for (int i = 0, j = 0; i < n && j < n;) {
// Find minimum increment required in
// either row or column
int diff = min(maxSum - sumRow[i],
maxSum - sumCol[j]);
// Add difference in corresponding cell,
// sumRow[] and sumCol[] array
matrix[i][j] += diff;
sumRow[i] += diff;
sumCol[j] += diff;
// Update the count variable
count += diff;
// If ith row satisfied, increment ith
// value for next iteration
if (sumRow[i] == maxSum)
++i;
// If jth column satisfied, increment
// jth value for next iteration
if (sumCol[j] == maxSum)
++j;
}
return count;
}
// Utility function to print matrix
void printMatrix(int matrix[][2], int n)
{
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j)
cout << matrix[i][j] << " ";
cout << "\n";
}
}
// Driver code
int main()
{
int matrix[][2] = { { 1, 2 },
{ 3, 4 } };
cout << findMinOpeartion(matrix, 2) << "\n";
1282
Chapter 183. Minimum operations required to make each row and column of matrix equals
printMatrix(matrix, 2);
return 0;
}
Java
1283
Chapter 183. Minimum operations required to make each row and column of matrix equals
1284
Chapter 183. Minimum operations required to make each row and column of matrix equals
C#
1285
Chapter 183. Minimum operations required to make each row and column of matrix equals
int maxSum = 0;
for (int i = 0; i < n; ++i)
{
maxSum = Math.Max(maxSum, sumRow[i]);
maxSum = Math.Max(maxSum, sumCol[i]);
}
int count = 0;
for (int i = 0, j = 0; i < n && j < n;)
{
// Find minimum increment
// required in either row
// or column
int diff = Math.Min(maxSum - sumRow[i],
maxSum - sumCol[j]);
// Add difference in
// corresponding cell,
// sumRow[] and sumCol[]
// array
matrix[i,j] += diff;
sumRow[i] += diff;
sumCol[j] += diff;
// Update the count
// variable
count += diff;
// If ith row satisfied,
// increment ith value
// for next iteration
if (sumRow[i] == maxSum)
++i;
// If jth column satisfied,
// increment jth value for
// next iteration
if (sumCol[j] == maxSum)
++j;
}
return count;
}
// Utility function to
// print matrix
static void printMatrix(int [,]matrix,
int n)
{
1286
Chapter 183. Minimum operations required to make each row and column of matrix equals
Output
4
4 3
3 4
Source
https://www.geeksforgeeks.org/minimum-operations-required-make-row-column-matrix-equals/
1287
Chapter 184
Input : mat[][] = 0 0 0 1 1
0 0 0 1 1
0 0 0 1 1
1 1 1 1 1
1 1 1 1 1
Output : 1
In one move, choose (3, 3) to make the
whole matrix consisting of only 1s.
Input : mat[][] = 0 0 1 1 1
0 0 0 1 1
0 0 0 1 1
1 1 1 1 1
1 1 1 1 1
Output : 3
The idea is to start from the end point (N – 1, M – 1) and traverse the matrix in reverse
1288
Chapter 184. Minimum operations required to set all elements of binary matrix
C++
1289
Chapter 184. Minimum operations required to set all elements of binary matrix
}
// Driven Program
int main()
{
bool mat[N][M] =
{
0, 0, 1, 1, 1,
0, 0, 0, 1, 1,
0, 0, 0, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1
};
cout << minOperation(mat) << endl;
return 0;
}
Python 3
1290
Chapter 184. Minimum operations required to set all elements of binary matrix
arr[k][h] = 0
else:
arr[k][h] = 1
return ans
# Driver Code
mat = [[ 0, 0, 1, 1, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]
M = 5
N = 5
print(minOperation(mat))
# This code is contributed
# by ChitraNayal
PHP
<?php
// PHP program to find minimum
// operations required to set
// all the element of binary matrix
$N = 5;
$M = 5;
// Return minimum operation
// required to make all 1s.
function minOperation(&$arr)
{
global $N, $M;
$ans = 0;
for ($i = $N - 1;
$i >= 0; $i--)
{
for ($j = $M - 1;
$j >= 0; $j--)
{
// check if this
// cell equals 0
if($arr[$i][$j] == 0)
{
// increase the
// number of moves
1291
Chapter 184. Minimum operations required to set all elements of binary matrix
$ans++;
// flip from this cell
// to the start point
for ($k = 0;
$k <= $i; $k++)
{
for ($h = 0;
$h <= $j; $h++)
{
// flip the cell
if ($arr[$k][$h] == 1)
$arr[$k][$h] = 0;
else
$arr[$k][$h] = 1;
}
}
}
}
}
return $ans;
}
// Driver Code
$mat = array(array(0, 0, 1, 1, 1),
array(0, 0, 0, 1, 1),
array(0, 0, 0, 1, 1),
array(1, 1, 1, 1, 1),
array(1, 1, 1, 1, 1));
echo minOperation($mat);
// This code is contributed
// by ChitraNayal
?>
Output:
1292
Chapter 184. Minimum operations required to set all elements of binary matrix
Source
https://www.geeksforgeeks.org/minimum-operations-required-set-elements-binary-matrix/
1293
Chapter 185
Input :{7, 6, 7, 9
1, 2, 3, 4
1, 2, 3, 6,
5, 6, 7, 1}
Output: 36
Approach: Traverse in the matrix apart from first row, last row, first column and last
column. Compute the product of the four adjacent numbers which are at mat[i-1][j],
mat[i+1][j], mat[i][j+1] and mat[i][j-1]. On each computation, if the product thus
formed is less than the previous minimum found, then replace the minimum variable with
the computed product.
Below is the implementation of the above approach:
1294
Chapter 185. Minimum product in a grid of adjacent elements
C++
Java
1295
Chapter 185. Minimum product in a grid of adjacent elements
1296
Chapter 185. Minimum product in a grid of adjacent elements
{4, 5, 6, 7},
{7, 8, 9, 12}};
System.out.println(minimumProduct(mat));
}
}
// This code is contributed
// by anuj_67.
C#
// C# program to find
// the minimum product
// of adjacent elements
using System;
class GFG
{
static int N = 3;
static int M = 4;
// Function to return the
// minimum product of
// adjacent elements
static int minimumProduct(int [,]mat)
{
// initial minimum
int minimum = int.MaxValue;
// Traverse in the matrix
// except the first, last row
// first and last coloumn
for (int i = 1;
i < N - 1; i++)
{
for (int j = 1;
j < M - 1; j++)
{
// product the the
// adjacent elements
int p = mat[i - 1, j] *
mat[i + 1, j] *
mat[i, j + 1] *
mat[i, j - 1];
// if the product is less
1297
Chapter 185. Minimum product in a grid of adjacent elements
Output:
384
Source
https://www.geeksforgeeks.org/minimum-product-in-a-grid-of-adjacent-elements/
1298
Chapter 186
Minimum queens required to cover all the squares of a chess board - GeeksforGeeks
Given the dimension of a chess board (N x M), determine the minimum number of queens
required to cover all the squares of the board. A queen can attack any square along its row,
column or diagonals.
Examples:
Input : N = 8, M = 8
Output : 5
Layout : Q X X X X X X X
X X Q X X X X X
X X X X Q X X X
X Q X X X X X X
X X X Q X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
Input : N = 3, M = 5
Output : 2
Layout : Q X X X X
X X X X X
X X X Q X
This article attempts to solve the problem in a very simple way without much optimization.
1299
Chapter 186. Minimum queens required to cover all the squares of a chess board
Step 1: Starting from any corner square of the board, find an ‘uncovered’ square
(Uncovered square is a square which isn’t attacked by any of the queens already
placed). If none found, goto Step 4.
Step 2: Place a Queen on this square and increment variable ‘count’ by 1.
Step 3: Repeat step 1.
Step 4: Now, you’ve got a layout where every square is covered. Therefore, the
value of ‘count’ can be the answer. However, you might be able to do better, as
there might exist a better layout with lesser number of queens. So, store this
‘count’ as the best value till now and proceed to find a better solution.
Step 5: Remove the last queen placed and place it in the next ‘uncovered’ cell.
Step 6: Proceed recursively and try out all the possible layouts. Finally, the one
with the least number of queens is the answer.
1300
Chapter 186. Minimum queens required to cover all the squares of a chess board
if (countSoFar >= minCount)
// We've already obtained a solution with lesser or
// same number of queens. Hence, no need to proceed.
return;
// Checks if there exists any unattacked cells.
findUnattackedCell : {
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
if (!isAttacked(i, j))
// Square (i, j) is unattacked.
break findUnattackedCell;
// All squares all covered. Hence, this
// is the best solution till now.
minCount = countSoFar;
storeLayout();
return;
}
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j) {
if (!isAttacked(i, j)) {
// Square (i, j) is unattacked.
// Therefore, place a queen here.
board[i][j] = true;
// Increment 'count' and proceed recursively.
placeQueen(countSoFar + 1);
// Remove this queen and attempt to
// find a better solution.
board[i][j] = false;
}
}
}
// Returns 'true' if the square (row, col) is
// being attacked by at least one queen.
static boolean isAttacked(int row, int col)
{
int i, j;
1301
Chapter 186. Minimum queens required to cover all the squares of a chess board
Output:
1302
Chapter 186. Minimum queens required to cover all the squares of a chess board
Layout:
Q X X X X X X X
X X Q X X X X X
X X X X Q X X X
X Q X X X X X X
X X X Q X X X X
X X X X X X X X
X X X X X X X X
X X X X X X X X
Improved By : sarthakmannaofficial
Source
https://www.geeksforgeeks.org/minimum-queens-required-to-cover-all-the-squares-of-a-chess-board/
1303
Chapter 187
Method 1 (Naive Approach): Check every possible submatrix in given 2D array. This
solution requires 4 nested loops and time complexity of this solution would be O(n^4).
Method 2 (Efficient Approach): Kadane’s algorithm for 1D array can be used to
reduce the time complexity to O(n^3). The idea is to fix the left and right columns one by
one and find the minimum sum contiguous rows for every left and right column pair. We
basically find top and bottom row numbers (which have minimum sum) for every fixed left
and right column pair. To find the top and bottom row numbers, calculate sun of elements in
every row from left to right and store these sums in an array say temp[]. So temp[i] indicates
sum of elements from left to right in row i. If we apply Kadane’s 1D algorithm on temp[],
and get the minimum sum subarray of temp, this minimum sum would be the minimum
possible sum with left and right as boundary columns. To get the overall minimum sum,
we compare this sum with the minimum sum so far.
1304
Chapter 187. Minimum sum submatrix in a given 2D array
1305
Chapter 187. Minimum sum submatrix in a given 2D array
1306
Chapter 187. Minimum sum submatrix in a given 2D array
Output:
Source
https://www.geeksforgeeks.org/minimum-sum-submatrix-given-2d-array/
1307
Chapter 188
0: Empty cell
So we have to determine what is the minimum time required so that all the oranges become
rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j],
[i,j-1], [i,j+1] (up, down, left and right). If it is impossible to rot every orange then simply
return -1.
Examples:
1308
Chapter 188. Minimum time required to rot all oranges
{1, 0, 0, 2, 1}};
Output:
All oranges cannot be rotten.
1) Create an empty Q.
2) Find all rotten oranges and enqueue them to Q. Also enqueue
a delimiter to indicate beginning of next time frame.
3) While Q is not empty do following
3.a) While delimiter in Q is not reached
(i) Dequeue an orange from queue, rot all adjacent oranges.
While rotting the adjacents, make sure that time frame
is incremented only once. And time frame is not icnremented
if there are no adjacent oranges.
3.b) Dequeue the old delimiter and enqueue a new delimiter. The
oranges rotten in previous time frame lie between the two
delimiters.
1309
Chapter 188. Minimum time required to rot all oranges
}
// Function to check whether there is still a fresh
// orange remaining
bool checkall(int arr[][C])
{
for (int i=0; i<R; i++)
for (int j=0; j<C; j++)
if (arr[i][j] == 1)
return true;
return false;
}
// This function finds if it is possible to rot all oranges or not.
// If possible, then it returns minimum time required to rot all,
// otherwise returns -1
int rotOranges(int arr[][C])
{
// Create a queue of cells
queue<ele> Q;
ele temp;
int ans = 0;
// Store all the cells having rotten orange in first time frame
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
if (arr[i][j] == 2)
{
temp.x = i;
temp.y = j;
Q.push(temp);
}
}
}
// Separate these rotten oranges from the oranges which will rotten
// due the oranges in first time frame using delimiter which is (-1, -1)
temp.x = -1;
temp.y = -1;
Q.push(temp);
// Process the grid while there are rotten oranges in the Queue
while (!Q.empty())
{
// This flag is used to determine whether even a single fresh
// orange gets rotten due to rotten oranges in current time
1310
Chapter 188. Minimum time required to rot all oranges
1311
Chapter 188. Minimum time required to rot all oranges
Java
1312
Chapter 188. Minimum time required to rot all oranges
1313
Chapter 188. Minimum time required to rot all oranges
int ans = 0;
// Store all the cells having rotten orange in first time frame
for (int i=0; i < R; i++)
for (int j=0; j < C; j++)
if (arr[i][j] == 2)
Q.add(new Ele(i,j));
// Separate these rotten oranges from the oranges which will rotten
// due the oranges in first time frame using delimiter which is (-1, -1)
Q.add(new Ele(-1,-1));
// Process the grid while there are rotten oranges in the Queue
while(!Q.isEmpty())
{
// This flag is used to determine whether even a single fresh
// orange gets rotten due to rotten oranges in current time
// frame so we can increase the count of the required time.
boolean flag = false;
// Process all the rotten oranges in current time frame.
while(!isDelim(Q.peek()))
{
temp = Q.peek();
// Check right adjacent cell that if it can be rotten
if(isValid(temp.x+1, temp.y+1) && arr[temp.x+1][temp.y] == 1)
{
if(!flag)
{
// if this is the first orange to get rotten, increase
// count and set the flag.
ans++;
flag = true;
}
// Make the orange rotten
arr[temp.x+1][temp.y] = 2;
// push the adjacent orange to Queue
temp.x++;
Q.add(new Ele(temp.x,temp.y));
// Move back to current cell
temp.x--;
}
// Check left adjacent cell that if it can be rotten
if (isValid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1)
{
1314
Chapter 188. Minimum time required to rot all oranges
if (!flag)
{
ans++;
flag = true;
}
arr[temp.x-1][temp.y] = 2;
temp.x--;
Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue
temp.x++;
}
// Check top adjacent cell that if it can be rotten
if (isValid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) {
if(!flag)
{
ans++;
flag = true;
}
arr[temp.x][temp.y+1] = 2;
temp.y++;
Q.add(new Ele(temp.x,temp.y)); // Push this cell to Queue
temp.y--;
}
// Check bottom adjacent cell if it can be rotten
if (isValid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1)
{
if (!flag)
{
ans++;
flag = true;
}
arr[temp.x][temp.y-1] = 2;
temp.y--;
Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue
}
Q.remove();
}
// Pop the delimiter
Q.remove();
// If oranges were rotten in current frame than separate the
// rotten oranges using delimiter for the next frame for processing.
if (!Q.isEmpty())
{
Q.add(new Ele(-1,-1));
}
1315
Chapter 188. Minimum time required to rot all oranges
// If Queue was empty than no rotten oranges left to process so exit
}
// Return -1 if all arranges could not rot, otherwise -1.s
return (checkAll(arr))? -1: ans;
}
// Drive program
public static void main(String[] args)
{
int arr[][] = { {2, 1, 0, 2, 1},
{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
int ans = rotOranges(arr);
if(ans == -1)
System.out.println("All oranges cannot rot");
else
System.out.println("Time required for all oranges to rot = " + ans);
}
}
//This code is contributed by Sumit Ghosh
Output:
Source
https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/
1316
Chapter 189
Simple solution of this problem consumes extra space, we traverse all right diagonal (right-
to-left) one-by-one. During the traversal of diagonal, first we push all the elements into the
stack and after we traverse it again and replace every element of diagonal with the stack
element.
Below is C++ implementation of above idea.
1317
Chapter 189. Mirror of matrix across diagonal
1318
Chapter 189. Mirror of matrix across diagonal
k = column;
while (i < n && k >= 0) {
mat[i++][k--] = s.top();
s.pop();
}
}
}
// Utility function to print a matrix
void printMatrix(int mat[][MAX], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
// driver program to test above function
int main()
{
int mat[][MAX] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int n = 4;
imageSwap(mat, n);
printMatrix(mat, n);
return 0;
}
Output:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
C++
1319
Chapter 189. Mirror of matrix across diagonal
Java
1320
Chapter 189. Mirror of matrix across diagonal
static void imageSwap(int mat[][], int n)
{
// traverse a matrix and swap
// mat[i][j] with mat[j][i]
for (int i = 0; i < n; i++)
for (int j = 0; j <= i; j++)
mat[i][j] = mat[i][j] + mat[j][i]
- (mat[j][i] = mat[i][j]);
}
// Utility function to print a matrix
static void printMatrix(int mat[][], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print( mat[i][j] + " ");
System.out.println();
}
}
// driver program to test above function
public static void main (String[] args)
{
int mat[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int n = 4;
imageSwap(mat, n);
printMatrix(mat, n);
}
}
// This code is contributed by anuj_67.
C#
1321
Chapter 189. Mirror of matrix across diagonal
// traverse a matrix and swap
// mat[i][j] with mat[j][i]
for (int i = 0; i < n; i++)
for (int j = 0; j <= i; j++)
mat[i,j] = mat[i,j] + mat[j,i]
- (mat[j,i] = mat[i,j]);
}
// Utility function to print a matrix
static void printMatrix(int [,]mat, int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
Console.Write( mat[i,j] + " ");
Console.WriteLine();
}
}
// driver program to test above function
public static void Main ()
{
int [,]mat = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
int n = 4;
imageSwap(mat, n);
printMatrix(mat, n);
}
}
// This code is contributed by anuj_67.
Output:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
1322
Chapter 189. Mirror of matrix across diagonal
Source
https://www.geeksforgeeks.org/mirror-matrix-across-diagonal/
1323
Chapter 190
Given a number N, find out the number of possible numbers of given length.
Examples:
For N=1, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N=2, number of possible numbers would be 36
Possible numbers: 00,08 11,12,14 22,21,23,25 and so on.
If we start with 0, valid numbers will be 00, 08 (count: 2)
If we start with 1, valid numbers will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers will be 55,54,52,56,58 (count: 5)
………………………………
1324
Chapter 190. Mobile Numeric Keypad Problem
………………………………
We need to print the count of possible numbers.
N = 1 is trivial case, number of possible numbers would be 10 (0, 1, 2, 3, …., 9)
For N > 1, we need to start from some button, then move to any of the four direction (up,
left, right or down) which takes to a valid button (should not go to *, #). Keep doing this
until N length number is obtained (depth first traversal).
Recursive Solution:
Mobile Keypad is a rectangular grid of 4X3 (4 rows and 3 columns)
Lets say Count(i, j, N) represents the count of N length numbers starting from position (i,
j)
If N = 1
Count(i, j, N) = 10
Else
Count(i, j, N) = Sum of all Count(r, c, N-1) where (r, c) is new
position after valid move of length 1 from current
position (i, j)
1325
Chapter 190. Mobile Numeric Keypad Problem
{
ro = i + row[move];
co = j + col[move];
if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
keypad[ro][co] != '*' && keypad[ro][co] != '#')
{
totalCount += getCountUtil(keypad, ro, co, n-1);
}
}
return totalCount;
}
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
// Base cases
if (keypad == NULL || n <= 0)
return 0;
if (n == 1)
return 10;
int i=0, j=0, totalCount = 0;
for (i=0; i<4; i++) // Loop on keypad row
{
for (j=0; j<3; j++) // Loop on keypad column
{
// Process for 0 to 9 digits
if (keypad[i][j] != '*' && keypad[i][j] != '#')
{
// Get count when number is starting from key
// position (i, j) and add in count obtained so far
totalCount += getCountUtil(keypad, i, j, n);
}
}
}
return totalCount;
}
// Driver program to test above function
int main(int argc, char *argv[])
{
char keypad[4][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}};
printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
1326
Chapter 190. Mobile Numeric Keypad Problem
Output:
Dynamic Programming
There are many repeated traversal on smaller paths (traversal for smaller N) to find all
possible longer paths (traversal for bigger N). See following two diagrams for example. In
this traversal, for N = 4 from two starting positions (buttons ‘4’ and ‘8’), we can see there
are few repeated traversals for N = 2 (e.g. 4 -> 1, 6 -> 3, 8 -> 9, 8 -> 7 etc).
1327
Chapter 190. Mobile Numeric Keypad Problem
Since the problem has both properties: Optimal Substructure and Overlapping Subproblems,
it can be efficiently solved using dynamic programming.
Following is C program for dynamic programming implementation.
1328
Chapter 190. Mobile Numeric Keypad Problem
count[i][0] = 0;
count[i][1] = 1;
}
// Bottom up - Get number count of length 2, 3, 4, ... , n
for (k=2; k<=n; k++)
{
for (i=0; i<4; i++) // Loop on keypad row
{
for (j=0; j<3; j++) // Loop on keypad column
{
// Process for 0 to 9 digits
if (keypad[i][j] != '*' && keypad[i][j] != '#')
{
// Here we are counting the numbers starting with
// digit keypad[i][j] and of length k keypad[i][j]
// will become 1st digit, and we need to look for
// (k-1) more digits
num = keypad[i][j] - '0';
count[num][k] = 0;
// move left, up, right, down from current location
// and if new location is valid, then get number
// count of length (k-1) from that new digit and
// add in count we found so far
for (move=0; move<5; move++)
{
ro = i + row[move];
co = j + col[move];
if (ro >= 0 && ro <= 3 && co >=0 && co <= 2 &&
keypad[ro][co] != '*' && keypad[ro][co] != '#')
{
nextNum = keypad[ro][co] - '0';
count[num][k] += count[nextNum][k-1];
}
}
}
}
}
}
// Get count of all possible numbers of length "n" starting
// with digit 0, 1, 2, ..., 9
totalCount = 0;
for (i=0; i<=9; i++)
totalCount += count[i][n];
return totalCount;
}
1329
Chapter 190. Mobile Numeric Keypad Problem
// Driver program to test above function
int main(int argc, char *argv[])
{
char keypad[4][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}};
printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
return 0;
}
Output:
1330
Chapter 190. Mobile Numeric Keypad Problem
1331
Chapter 190. Mobile Numeric Keypad Problem
}
else
{
for (i=0; i<=9; i++)
totalCount += odd[i];
}
return totalCount;
}
// Driver program to test above function
int main()
{
char keypad[4][3] = {{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
printf("Count for numbers of length %d: %dn", 1, getCount(keypad, 1));
printf("Count for numbers of length %d: %dn", 2, getCount(keypad, 2));
printf("Count for numbers of length %d: %dn", 3, getCount(keypad, 3));
printf("Count for numbers of length %d: %dn", 4, getCount(keypad, 4));
printf("Count for numbers of length %d: %dn", 5, getCount(keypad, 5));
return 0;
}
Output:
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/mobile-numeric-keypad-problem/
1332
Chapter 191
Move matrix elements in given direction and add elements with same value - GeeksforGeeks
Given a matrix m[ ][ ] of size n x n consisting of integers and given a character ‘x’ indi-
cating the direction. Value of ‘x’ can be ‘u’, ‘d’, ‘l’, ‘r’ indicating Up, Down, Left, Right
correspondingly. The task is to move the element to given direction such that the consecu-
tive elements having same value are added into single value and shift the rest element. Also,
shift the element if the next element in given direction is 0.
For example :
Consider x = ‘l’ and matrix m[][],
32 3 3
001
10 10 8
After adding 3 in first row, 10 in third row and moving 1 in second row,
Matrix will become
32 6 0
100
20 8 0
Examples :
Input : x = 'l'
m[][] = { { 32, 3, 3, 3, 3 },
{ 0, 0, 1, 0, 0 },
{ 10, 10, 8, 1, 2},
{ 0, 0, 0, 0, 1},
{ 4, 5, 6, 7, 8 } }
1333
Chapter 191. Move matrix elements in given direction and add elements with same value
Output :
32 6 6 0 0
1 0 0 0 0
20 8 1 2 0
1 0 0 0 0 0
4 5 6 7 8
Input : x = 'u'
m[][] = { { 10, 3, 32 },
{ 10, 0, 96 },
{ 5, 32, 96 } }
Output :
20 3 32
5 32 192
0 0 0
Approach : The idea is to traverse each row or column (depending on given direction)
from side x of row or column towards x’ (opposite of x). For example, if given value of x
is ‘l’ (left) then start scanning each row from left side to right. While traversing, store row
or column element in temporary 1-D array (say temp[]) by skipping elements having value
0 and sum of consecutive element if they have equal value. After that, start copying the
temporary array temp[0..k] to the current row or column from the x side (of row or column)
to x’ (opposite of x) and fill reset of the element by 0.
Let, x = ‘l’ i.e move towards left. So, start coping each row from left most index to right
most index of the row and store in temporary array with processing of ignoring 0s and adding
two consecutive element into one if they have same value. Below is the illustration for row 1,
Now, for each, copy temporary array to current row from left most index to right most
index. Below is illustration for row 1,
1334
Chapter 191. Move matrix elements in given direction and add elements with same value
1335
Chapter 191. Move matrix elements in given direction and add elements with same value
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have same
// value at consecutive position.
if (j < v.size() - 1 &&
v[j] == v[j + 1])
{
// insert only one element
// as sum of two same element.
w.push_back(2 * v[j]);
j++;
}
else
w.push_back(v[j]);
}
// filling the each row element to 0.
for (j = 0; j < n; j++)
a[i][j] = 0;
j = n - 1;
// Copying the temporary
// array to the current row.
for (auto it = w.begin();
it != w.end(); it++)
a[i][j--] = *it;
}
}
// for left shift move
else if (d[0] == 'l')
{
// for each row
for (int i = 0; i < n; i++)
{
vector<int> v, w;
int j;
// for each element of the
// row from left to right
for (j = 0; j < n; j++)
{
// if not 0
1336
Chapter 191. Move matrix elements in given direction and add elements with same value
if (a[i][j])
v.push_back(a[i][j]);
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have same
// value at consecutive position.
if (j < v.size() - 1 &&
v[j] == v[j + 1])
{
// insert only one element
// as sum of two same element.
w.push_back(2 * v[j]);
j++;
}
else
w.push_back(v[j]);
}
// filling the each row element to 0.
for (j = 0; j < n; j++)
a[i][j] = 0;
j = 0;
for (auto it = w.begin();
it != w.end(); it++)
a[i][j++] = *it;
}
}
// for down shift move.
else if (d[0] == 'd')
{
// for each column
for (int i = 0; i < n; i++)
{
vector<int> v, w;
int j;
// for each element of
// column from bottom to top
for (j = n - 1; j >= 0; j--)
{
// if not 0
if (a[j][i])
1337
Chapter 191. Move matrix elements in given direction and add elements with same value
v.push_back(a[j][i]);
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have same
// value at consecutive position.
if (j < v.size() - 1 &&
v[j] == v[j + 1])
{
// insert only one element
// as sum of two same element.
w.push_back(2 * v[j]);
j++;
}
else
w.push_back(v[j]);
}
// filling the each column element to 0.
for (j = 0; j < n; j++)
a[j][i] = 0;
j = n - 1;
// Copying the temporary array
// to the current column
for (auto it = w.begin();
it != w.end(); it++)
a[j--][i] = *it;
}
}
// for up shift move
else if (d[0] == 'u')
{
// for each column
for (int i = 0; i < n; i++)
{
vector<int> v, w;
int j;
// for each element of column
// from top to bottom
for (j = 0; j < n; j++)
{
1338
Chapter 191. Move matrix elements in given direction and add elements with same value
// if not 0
if (a[j][i])
v.push_back(a[j][i]);
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have same
// value at consecutive position.
if (j < v.size() - 1 &&
v[j] == v[j + 1])
{
// insert only one element
// as sum of two same element.
w.push_back(2 * v[j]);
j++;
}
else
w.push_back(v[j]);
}
// filling the each column element to 0.
for (j = 0; j < n; j++)
a[j][i] = 0;
j = 0;
// Copying the temporary array
// to the current column
for (auto it = w.begin();
it != w.end(); it++)
a[j++][i] = *it;
}
}
}
// Driven Program
int main()
{
char d[2] = "l";
int n = 4;
int a[MAX][MAX] = { { 32, 3, 3, 3, 3 },
{ 0, 0, 1, 0, 0 },
{ 10, 10, 8, 1, 2 },
{ 0, 0, 0, 0, 1 },
{ 4, 5, 6, 7, 8 } };
1339
Chapter 191. Move matrix elements in given direction and add elements with same value
moveMatrix(d, n, a);
// Printing the final array
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Java
1340
Chapter 191. Move matrix elements in given direction and add elements with same value
// if not 0
if (a[i][j] != 0)
v.add(a[i][j]);
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have
// same value at
// consecutive position.
if (j < v.size() - 1 &&
v.get(j) == v.get(j + 1))
{
// insert only one element
// as sum of two same element.
w.add(2 * v.get(j));
j++;
}
else
w.add(v.get(j));
}
// filling the each
// row element to 0.
for (j = 0; j < n; j++)
a[i][j] = 0;
j = n - 1;
// Copying the temporary
// array to the current row.
for (int it = 0; it < w.size(); it++)
a[i][j--] = w.get(it);
}
}
// for left shift move
else if (d == 'l')
{
// for each row
for (int i = 0; i < n; i++)
{
ArrayList<Integer> v =
new ArrayList<Integer>();
ArrayList<Integer> w =
new ArrayList<Integer>();
1341
Chapter 191. Move matrix elements in given direction and add elements with same value
int j;
// for each element of the
// row from left to right
for (j = 0; j < n; j++)
{
// if not 0
if (a[i][j] != 0)
v.add(a[i][j]);
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have
// same value at
// consecutive position.
if (j < v.size() - 1 &&
v.get(j) == v.get(j + 1))
{
// insert only one
// element as sum
// of two same element.
w.add(2 * v.get(j));
j++;
}
else
w.add(v.get(j));
}
// filling the each
// row element to 0.
for (j = 0; j < n; j++)
a[i][j] = 0;
j = 0;
for (int it = 0; it < w.size(); it++)
a[i][j++] = w.get(it);
}
}
// for down shift move.
else if (d == 'd')
{
// for each column
for (int i = 0; i < n; i++)
{
1342
Chapter 191. Move matrix elements in given direction and add elements with same value
ArrayList<Integer> v =
new ArrayList<Integer>();
ArrayList<Integer> w =
new ArrayList<Integer>();
int j;
// for each element of
// column from bottom to top
for (j = n - 1; j >= 0; j--)
{
// if not 0
if (a[j][i] != 0)
v.add(a[j][i]);
}
// for each temporary array
for (j = 0; j < v.size(); j++)
{
// if two element have
// same value at consecutive
// position.
if (j < v.size() - 1 &&
v.get(j) == v.get(j + 1))
{
// insert only one element
// as sum of two same element.
w.add(2 * v.get(j));
j++;
}
else
w.add(v.get(j));
}
// filling the each
// column element to 0.
for (j = 0; j < n; j++)
a[j][i] = 0;
j = n - 1;
// Copying the temporary array
// to the current column
for (int it = 0; it < w.size(); it++)
a[j--][i] = w.get(it);
}
}
1343
Chapter 191. Move matrix elements in given direction and add elements with same value
1344
Chapter 191. Move matrix elements in given direction and add elements with same value
// column
for (int it = 0; it < w.size(); it++)
a[j++][i] = w.get(it);
}
}
}
// Driver Code
public static void main(String args[])
{
char d = 'l';
int n = 4;
int a[][] = {{ 32, 3, 3, 3, 3},
{ 0, 0, 1, 0, 0},
{ 10, 10, 8, 1, 2},
{ 0, 0, 0, 0, 1},
{ 4, 5, 6, 7, 8}};
moveMatrix(d, n, a);
// Printing the
// final array
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
C#
1345
Chapter 191. Move matrix elements in given direction and add elements with same value
int [,]a)
{
// For right shift move.
if (d == 'r')
{
// for each row from
// top to bottom
for (int i = 0; i < n; i++)
{
List<int> v = new List<int>();
List<int> w = new List<int>();
int j;
// for each element of
// row from right to left
for (j = n - 1; j >= 0; j--)
{
// if not 0
if (a[i, j] != 0)
v.Add(a[i, j]);
}
// for each temporary array
for (j = 0; j < v.Count; j++)
{
// if two element have
// same value at
// consecutive position.
if (j < v.Count - 1 &&
v[j] == v[j + 1])
{
// insert only one element
// as sum of two same element.
w.Add(2 * v[j]);
j++;
}
else
w.Add(v[j]);
}
// filling the each
// row element to 0.
for (j = 0; j < n; j++)
a[i, j] = 0;
j = n - 1;
1346
Chapter 191. Move matrix elements in given direction and add elements with same value
// Copying the temporary
// array to the current row.
for (int it = 0; it < w.Count; it++)
a[i, j--] = w[it];
}
}
// for left shift move
else if (d == 'l')
{
// for each row
for (int i = 0; i < n; i++)
{
List<int> v = new List<int>();
List<int> w = new List<int>();
int j;
// for each element of the
// row from left to right
for (j = 0; j < n; j++)
{
// if not 0
if (a[i, j] != 0)
v.Add(a[i, j]);
}
// for each temporary array
for (j = 0; j < v.Count; j++)
{
// if two element have
// same value at
// consecutive position.
if (j < v.Count - 1 &&
v[j] == v[j + 1])
{
// insert only one element
// as sum of two same element.
w.Add(2 * v[j]);
j++;
}
else
w.Add(v[j]);
}
// filling the each
// row element to 0.
1347
Chapter 191. Move matrix elements in given direction and add elements with same value
1348
Chapter 191. Move matrix elements in given direction and add elements with same value
1349
Chapter 191. Move matrix elements in given direction and add elements with same value
// filling the each
// column element to 0.
for (j = 0; j < n; j++)
a[j, i] = 0;
j = 0;
// Copying the temporary array
// to the current column
for (int it = 0; it < w.Count; it++)
a[j++, i] = w[it];
}
}
}
// Driven Code
static void Main()
{
char d = 'l';
int n = 4;
int [,]a = new int[,]{{ 32, 3, 3, 3, 3},
{ 0, 0, 1, 0, 0},
{ 10, 10, 8, 1, 2},
{ 0, 0, 0, 0, 1},
{ 4, 5, 6, 7, 8}};
moveMatrix(d, n, a);
// Printing the final array
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(a[i, j] + " ");
Console.WriteLine();
}
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// PHP code to move matrix
// elements in given
1350
Chapter 191. Move matrix elements in given direction and add elements with same value
1351
Chapter 191. Move matrix elements in given direction and add elements with same value
1352
Chapter 191. Move matrix elements in given direction and add elements with same value
array_push($w, $v[$j]);
}
// filling the each
// row element to 0.
for ($j = 0; $j < $n; $j++)
$a[$i][$j] = 0;
$j = 0;
for ($it = 0; $it != count($w); $it++)
$a[$i][$j++] = $w[$it];
}
}
// for down shift move.
else if ($d[0] == 'd')
{
// for each column
for ($i = 0; $i < $n; $i++)
{
$v = array(); $w = array();
$j = 0;
// for each element
// of column from
// bottom to top
for ($j = $n - 1; $j >= 0; $j--)
{
// if not 0
if ($a[$j][$i])
array_push($v, $a[$j][$i]);
}
// for each temporary array
for ($j = 0; $j < count($v); $j++)
{
// if two element have
// same value at
// consecutive position.
if ($j < count($v) - 1 &&
$v[$j] == $v[$j + 1])
{
// insert only one element
// as sum of two same element.
array_push($w, 2 * $v[$j]);
$j++;
1353
Chapter 191. Move matrix elements in given direction and add elements with same value
}
else
array_push($w, $v[$j]);
}
// filling the each
// column element to 0.
for ($j = 0; $j < $n; $j++)
$a[$j][$i] = 0;
$j = $n - 1;
// Copying the temporary array
// to the current column
for ($it = 0; $it != count($w); $it++)
$a[$j--][$i] = $w[$it];
}
}
// for up shift move
else if ($d[0] == 'u')
{
// for each column
for ($i = 0; $i < $n; $i++)
{
$v = array(); $w = array();
$j = 0;
// for each element of column
// from top to bottom
for ($j = 0; $j < $n; $j++)
{
// if not 0
if ($a[$j][$i])
array_push($v,
$a[$j][$i]);
}
// for each temporary array
for ($j = 0; $j < count($v); $j++)
{
// if two element have same
// value at consecutive position.
if ($j < count($v) - 1 &&
$v[$j] == $v[$j + 1])
{
// insert only one element
// as sum of two same element.
1354
Chapter 191. Move matrix elements in given direction and add elements with same value
array_push($w, 2 * $v[$j]);
$j++;
}
else
array_push($w, $v[$j]);
}
// filling the each
// column element to 0.
for ($j = 0; $j < $n; $j++)
$a[$j][$i] = 0;
$j = 0;
// Copying the temporary array
// to the current column
for ($it = 0; $it != count($w); $it++)
$a[$j++][$i] = $w[$it];
}
}
}
// Driven Code
$d = array("l");
$n = 4;
$a = array( array(32, 3, 3, 3, 3),
array(0, 0, 1, 0, 0),
array(10, 10, 8, 1, 2),
array(0, 0, 0, 0, 1),
array(4, 5, 6, 7, 8));
moveMatrix($d, $n, $a);
// Printing the final array
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
echo ($a[$i][$j]." ");
echo ("\n");
}
// This code is contributed
// by Manish Shaw(manishshaw1)
?>
Output:
1355
Chapter 191. Move matrix elements in given direction and add elements with same value
32 6 3 0
1 0 0 0
20 8 1 0
0 0 0 0
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/move-matrix-elements-given-direction-add-elements-value/
1356
Chapter 192
1357
Chapter 192. Multiplication of Matrix using pthreads
Examples:
Input :
Matrix A
1 0 0
0 1 0
0 0 1
Matrix B
2 3 2
4 5 1
7 8 6
1358
Chapter 192. Multiplication of Matrix using pthreads
1359
Chapter 192. Multiplication of Matrix using pthreads
Output:
Matrix A
3 7 3 6
9 2 0 3
0 2 1 7
2 2 7 9
Matrix B
6 5 5 2
1 7 9 6
6 6 8 9
0 3 5 2
Multiplication of A and B
43 100 132 87
56 68 78 36
8 41 61 35
56 93 129 97
Source
https://www.geeksforgeeks.org/multiplication-matrix-using-pthreads/
1360
Chapter 193
1361
Chapter 193. Multiplication of two Matrices in Single line using Numpy in Python
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2 = [[5,8,1],
[6,7,3],
[4,5,9]]
res = [[0 for x in range(3)] for y in range(3)]
# explicit for loops
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
# resulted matrix
res[i][j] += matrix1[i][k] * matrix2[k][j]
print (res)
Output:
In this program, we have used nested for loops for computation of result which will iterate
through each row and column of the matrices, at last it will accumulate the sum of product
in the result.
2. Using Numpy : Multiplication using Numpy also know as vectorization which main
aim to reduce or remove the explicit use of for loops in the program by which computation
becomes faster.
Numpy is a build in a package in python for array-processing and manipulation.For larger
matrix operations we use numpy python package which is 1000 times faster than iterative
one method.
For detail about Numpy please visit the Link
1362
Chapter 193. Multiplication of two Matrices in Single line using Numpy in Python
Output:
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]
In the above example we have used dot product and in mathematics the dot product is an
algebraic operation that takes two vectors of equal size and returns a single number. The
result is calculated by multiplying corresponding entries and adding up those products.
Source
https://www.geeksforgeeks.org/multiplication-two-matrices-single-line-using-numpy-python/
1363
Chapter 194
Place(k, i)
// Returns true if a queen can be placed
// in kth row and ith column. Otherwise it
// returns false. X[] is a global array
// whose first (k-1) values have been set.
// Abs( ) returns absolute value of r
{
for j := 1 to k-1 do
return true;
}
Algorithm nQueens(k, n) :
1364
Chapter 194. N Queen in O(n) space
C++
1365
Chapter 194. N Queen in O(n) space
Output:
---------------------------------
Arrangement No. 1
---------------------------------
_ Q _ _
_ _ _ Q
Q _ _ _
_ _ Q _
---------------------------------
---------------------------------
Arrangement No. 2
1366
Chapter 194. N Queen in O(n) space
---------------------------------
_ _ Q _
Q _ _ _
_ _ _ Q
_ Q _ _
---------------------------------
Source
https://www.geeksforgeeks.org/n-queen-in-on-space/
1367
Chapter 195
Input : N = 8
Output : 2/3
Input : N = 15
Output : 1/5
See image for reference of counting.
1368
Chapter 195. N-th term of George Cantor set of rational numbers
Here the first term is 1/1, second term is 1/2, third term is 2/1, fourth term is 3/1, fifth
term is 2/2, sixth term is 1/3 so on……
C++
1369
Chapter 195. N-th term of George Cantor set of rational numbers
void georgeCantor(int n)
{
int i = 1; // let i = numerator
int j = 1; // let j = denominator
int k = 1; // to keep the check of no. of terms
// loop till k is not equal to n
while (k < n)
{
j++ , k++;
// check if k is already equal to N
// then the first term is the required
// rational number
if (k == n)
break;
// loop for traversing from right to left
// downwards diagonally
while (j > 1 && k < n) {
i++, j--, k++;
}
if (k == n)
break;
i++, k++;
if (k == n)
break;
// loop for traversing from left
// to right upwards diagonally
while (i > 1 && k < n) {
i--, j++, k++;
}
}
cout << "N-th term : "<<i<<" / "<<j;
}
// driver code
int main()
{
int n = 15;
georgeCantor(n);
return 0;
}
1370
Chapter 195. N-th term of George Cantor set of rational numbers
Java
1371
Chapter 195. N-th term of George Cantor set of rational numbers
Python3
1372
Chapter 195. N-th term of George Cantor set of rational numbers
# loop for traversing from right
# to left downwards diagonally
while j > 1 and k < n:
i += 1
j -= 1
k += 1
if k == n:
break
i += 1
k += 1
if k == n:
break
# loop for traversing from left
# to right upwards diagonally
while i > 1 and k < n:
i -= 1
j += 1
k += 1
print ("N-th term : %d/%d"%(i, j))
# Driver code
n = 15
georgeCantor(n)
# This code is contributed
# by Shreyanshi Arun
C#
1373
Chapter 195. N-th term of George Cantor set of rational numbers
1374
Chapter 195. N-th term of George Cantor set of rational numbers
int n = 15;
georgeCantor(n);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to find N-th
// term in George Cantor set
// of rational numbers
function georgeCantor($n)
{
$i = 1; // let i = numerator
$j = 1; // let j = denominator
// to keep the check
// of no. of terms
$k = 1;
// loop till k is
// not equal to n
while ($k < $n)
{
$j++ ; $k++;
// check if k is already equal
// to N then the first term is
// the required rational number
if ($k == $n)
break;
// loop for traversing from right
// to left downwards diagonally
while ($j > 1 && $k < $n)
{
$i++; $j--; $k++;
}
if ($k == $n)
break;
$i++; $k++;
1375
Chapter 195. N-th term of George Cantor set of rational numbers
Output :
Improved By : jit_t
Source
https://www.geeksforgeeks.org/n-th-term-of-george-cantor-set-of-rational-numbers/
1376
Chapter 196
Input : m = 3, n = 4
mat[m][n] = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 0}}
Output: 3 2 1 0
2 1 0 0
1 0 0 1
A simple solution for this problem is to for each 0 in the matrix recursively check the
nearest 1 in the matrix.
An efficient solution solution for this problem is to use BFS. Here is the algorithm to
solve this problem :
1377
Chapter 196. Nearest 1 in a binary matrix
adjacent in the queue to complete the BFS traversal and filling the complete distance
matrix.
• After completing the BFS traversal each cell of distance matrix will contain the dis-
tance of nearest ‘1’.
1378
Chapter 196. Nearest 1 in a binary matrix
// pop element from queue one by one untill it gets empty
// pair element to hold the currently poped element
pair<int ,int> poped;
while (!q.empty())
{
poped = q.front();
q.pop();
// coordinate of currently poped node
int x = poped.first;
int y = poped.second;
// now check for all adjancent of poped element
for (int i=0; i<4; i++)
{
int adjx = x + newx[i];
int adjy = y + newy[i];
// if new coordinates are within boundry and
// we can minimize the distance of adjancent
// then update the distnace of adjacent in
// distance matrix and push this adjacent
// element in queue for further bfs
if (adjx>=0 && adjx<m && adjy>=0 && adjy<n &&
dist[adjx][adjy] > dist[x][y] + 1)
{
// update distance
dist[adjx][adjy] = dist[x][y] + 1;
q.push(make_pair(adjx,adjy));
}
}
}
}
// Driver program to run the case
int main()
{
int m = 3, n = 4;
int mat[][MAX] = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 0}
};
// Fills values in dist[][]
nearestOne(mat, m, n);
// print distance matrix
for (int i=0; i<m; i++)
1379
Chapter 196. Nearest 1 in a binary matrix
{
for (int j=0; j<n; j++)
cout << dist[i][j] << " ";
cout << endl;
}
return 0;
}
Output:
3 2 1 0
2 1 0 0
1 0 0 1
Source
https://www.geeksforgeeks.org/nearest-1-0-binary-matrix/
1380
Chapter 197
Number of cells a queen can move with obstacles on the chessborad - GeeksforGeeks
Consider a N X N chessboard with a Queen and K obstacles. The Queen cannot pass
through obstacles. Given the position (x, y) of Queen, the task is to find the number of
cells the queen can move.
Examples:
Input : N = 8, x = 4, y = 4,
K = 0
Output : 27
Input : N = 8, x = 4, y = 4,
K = 1, kx1 = 3, ky1 = 5
Output : 24
Method 1:
The idea is to iterate over the cells the queen can attack and stop until there is an obstacle
or end of the board. To do that, we need to iterate horizontally, vertically and diagonally.
The moves from position (x, y) can be:
(x+1, y): one step horizontal move to the right.
(x-1, y): one step horizontal move to the left.
(x+1, y+1): one step diagonal move up-right.
(x-1, y-1): one step diagonal move down-left.
1381
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
1382
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
}
// Fetching number of position a queen can
// move in each direction.
ans += check(n, x + 1, y, 1, 0, mp);
ans += check(n, x-1, y, -1, 0, mp);
ans += check(n, x, y + 1, 0, 1, mp);
ans += check(n, x, y-1, 0, -1, mp);
ans += check(n, x + 1, y + 1, 1, 1, mp);
ans += check(n, x + 1, y-1, 1, -1, mp);
ans += check(n, x-1, y + 1, -1, 1, mp);
ans += check(n, x-1, y-1, -1, -1, mp);
return ans;
}
// Driven Program
int main()
{
int n = 8; // Chessboard size
int k = 1; // Number of obstacles
int Qposx = 4; // Queen x position
int Qposy = 4; // Queen y position
int obstPosx[] = { 3 }; // x position of obstacles
int obstPosy[] = { 5 }; // y position of obstacles
cout << numberofPosition(n, k, Qposx, Qposy,
obstPosx, obstPosy) << endl;
return 0;
}
Output:
24
Method 2:
The idea is to iterate over the obstacles and for those who are in the queen’s path, we
calculate the free cells upto that obstacle. If there is no obstacle in the path we have to
calculate the number of free cells upto end of board in that direction.
For any (x1 , y1 ) and (x2 , y2 ):
1383
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
C++
1384
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
Java
1385
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
1386
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
}
return d11 + d12 + d21 + d22 + r1 + r2 + c1 + c2;
}
// Driver code
public static void main (String[] args) {
int n = 8; // Chessboard size
int k = 1; // number of obstacles
int Qposx = 4; // Queen x position
int Qposy = 4; // Queen y position
int obstPosx[] = { 3 }; // x position of obstacles
int obstPosy[] = { 5 }; // y position of obstacles
System.out.println(numberofPosition(n, k, Qposx,
Qposy, obstPosx, obstPosy));
}
}
// This code is contributed by anuj_67.
C#
1387
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
r2 = n-y;
c1 = x-1;
c2 = n-x;
// For each obstacle find the Minimum distance.
// If obstacle is present in any direction,
// distance will be updated.
for (int i = 0; i < k; i++)
{
if ( x > obstPosx[i] && y > obstPosy[i] &&
x-obstPosx[i] == y-obstPosy[i] )
d11 = Math.Min(d11, x-obstPosx[i]-1);
if ( obstPosx[i] > x && obstPosy[i] > y &&
obstPosx[i]-x == obstPosy[i]-y )
d12 = Math.Min( d12, obstPosx[i]-x-1);
if ( obstPosx[i] > x && y > obstPosy[i] &&
obstPosx[i]-x == y-obstPosy[i] )
d21 = Math.Min(d21, obstPosx[i]-x-1);
if ( x > obstPosx[i] && obstPosy[i] > y &&
x-obstPosx[i] == obstPosy[i]-y)
d22 = Math.Min(d22, x-obstPosx[i]-1);
if ( x == obstPosx[i] && obstPosy[i] < y )
r1 = Math.Min(r1, y-obstPosy[i]-1);
if ( x == obstPosx[i] && obstPosy[i] > y )
r2 = Math.Min(r2, obstPosy[i]-y-1);
if ( y == obstPosy[i] && obstPosx[i] < x )
c1 = Math.Min(c1, x-obstPosx[i]-1);
if ( y == obstPosy[i] && obstPosx[i] > x )
c2 = Math.Min(c2, obstPosx[i]-x-1);
}
return d11 + d12 + d21 + d22 + r1 + r2 + c1 + c2;
}
// Driver code
public static void Main ()
{
int n = 8; // Chessboard size
int k = 1; // number of obstacles
int Qposx = 4; // Queen x position
int Qposy = 4; // Queen y position
1388
Chapter 197. Number of cells a queen can move with obstacles on the chessborad
Improved By : vt_m
Source
https://www.geeksforgeeks.org/number-cells-queen-can-move-obstacles-chessborad/
1389
Chapter 198
Input : n = 3
H H H
H U H
H H H
Output : 1
Only 1 day is required to turn all the
chocolates unhealthy in the chocolate box.
Input : n = 4
H H H U
H H H H
H U H H
H H H H
Output : 2
Explanation:
In first day chocolate at (0, 0), (0, 1),
(2, 3), (3, 3) will remain healthy and in
1390
Chapter 198. Number of days until all chocolates become unhealthy
1391
Chapter 198. Number of days until all chocolates become unhealthy
1392
Chapter 198. Number of days until all chocolates become unhealthy
}
// Check if there was any chocoloate
// marked unhealthy in current day
if (Hflag)
numdays++;
else
break;
}
return numdays;
}
// Driver function
int main()
{
int n = 4;
char arr[4][4] = { 'H', 'H', 'H', 'U',
'H', 'H', 'H', 'H',
'H', 'U', 'H', 'H',
'H', 'H', 'H', 'H'
};
int ans = numdays(arr, n);
cout << "number of days taken : "
<< ans << "\n";
return 0;
}
Output:
1393
Chapter 198. Number of days until all chocolates become unhealthy
1394
Chapter 198. Number of days until all chocolates become unhealthy
1395
Chapter 198. Number of days until all chocolates become unhealthy
}
return numdays - 1;
}
// Driver function
int main()
{
int n = 4;
char arr[4][4] = { 'H', 'H', 'H', 'U',
'H', 'H', 'H', 'H',
'H', 'H', 'U', 'H',
'H', 'H', 'H', 'H' };
int ans = numdays(arr, n);
cout << "number of days taken : "
<< ans << "\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-of-days-until-all-chocolates-become-unhealthy/
1396
Chapter 199
We can solve this problem using DFS. In path from source to destination we can see that
whenever we have more than 1 neighbors, we need to decide our path so first we do a DFS
and store the path from source to the destination in terms of child-parent array and then
we move from destination to source, cell by cell using parent array and at every cell where
we have more than 1 neighbors we will increase our answer by 1.
Please see below code for better understanding.
1397
Chapter 199. Number of decisions to reach destination
1398
Chapter 199. Number of decisions to reach destination
start = i*N + j;
g[i*N + j].clear();
if (grid[i][j] != 'B')
{
for (int k = 0; k < 4; k++)
{
int u = i + dx[k];
int v = j + dy[k];
// if neighboring cell is in boundry
// and doesn't have 'B'
if (u >= 0 && u < M && v >= 0 &&
v < N && grid[u][v] != 'B')
g[i*N + j].push_back(u*N + v);
}
}
}
}
// call dfs from start and fill up parent array
dfs(start, g, part, visit);
int curr = dest;
int res = 0;
// loop from destination cell back to start cell
while (curr != start)
{
/* if current cell has more than 2 neighbors,
then we need to decide our path to reach S
from D, so increase result by 1 */
if (g[curr].size() > 2)
res++;
curr = prt[curr];
}
return res;
}
// Driver code to test above methods
int main()
{
string grid[] =
{
".BBB.B.BB",
".....B.B.",
1399
Chapter 199. Number of decisions to reach destination
"B.B.B.BSB",
".DB......"
};
int M = sizeof(grid)/sizeof(grid[0]);
cout << turnsToReachDestination(grid, M) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-decisions-reach-destination/
1400
Chapter 200
Examples :
Find sum of all row-wise minimum and sum of all column-wise maximum. Take the mean
of this sum by dividing the sum value with (n+m) i.e., total number of rows and columns.
Now, as we have the mean of row-wise minimum and column-wise maximum, iterate over
the matrix to find the number of elements greater than calculated mean.
Below is the implementation of above approach:
1401
Chapter 200. Number of elements greater than modified mean in matrix
C++
1402
Chapter 200. Number of elements greater than modified mean in matrix
return count;
}
// driver function
int main()
{
int mat[n][m] = { 5, 4, 2, 8, 7,
1, 5, 8, 3, 4,
8, 5, 4, 6, 0,
2, 5, 8, 9, 4 };
cout << countElements(mat);
return 0;
}
Java
1403
Chapter 200. Number of elements greater than modified mean in matrix
C#
1404
Chapter 200. Number of elements greater than modified mean in matrix
class GFG {
static int n = 4, m = 5;
// function to count elements
// greater than mean
static int countElements(int [,]mat)
{
// For each row find minimum
// element and add to rowSum
int rowSum = 0;
for (int i = 0; i < n; i++)
{
int min = mat[i,0];
for (int j = 1; j < m; j++)
if (mat[i,j] < min)
min = mat[i,j];
rowSum += min;
}
// For each column find maximum
// element and add to colSum
int colSum = 0;
for (int i = 0; i < m; i++) {
int max = mat[0,i];
for (int j = 1; j < n; j++)
if (max < mat[j,i])
max = mat[j,i];
colSum += max;
}
// Calculate mean of row-wise minimum
// and column wise maximum
int mean = (rowSum + colSum) / (m + n);
// For whole matrix count
// elements greater than mean
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (mean < mat[i,j])
count++;
1405
Chapter 200. Number of elements greater than modified mean in matrix
return count;
}
// Driver function
public static void Main()
{
int [,]mat = {{5, 4, 2, 8, 7},
{1, 5, 8, 3, 4},
{8, 5, 4, 6, 0},
{2, 5, 8, 9, 4}};
Console.Write(countElements(mat));
}
}
// This article is contribute by nitin mittal.
PHP
<?php
// PHP program to count number of
// elements greater than mean
// define constant for
// row and column
$n = 4;
$m = 5;
// function to count elements
// greater than mean
function countElements($mat)
{
// For each row find minimum
// element and add to rowSum
$rowSum = 0;
global $n, $m;
for ($i = 0; $i < $n; $i++)
{
$min = $mat[$i][0];
for ($j = 1; $j < $m; $j++)
if ($mat[$i][$j] < $min)
$min = $mat[$i][$j];
$rowSum += $min;
}
// For each column find maximum
// element and add to colSum
$colSum = 0;
1406
Chapter 200. Number of elements greater than modified mean in matrix
Output:
11
Source
https://www.geeksforgeeks.org/find-number-elements-greater-modified-mean-matrix/
1407
Chapter 201
Input : N = 2
Allowed path 1: (1, 1) (1, 2)
Allowed path 2: (1, 2) (2, 2)
Output : 6
Cell (2, 1) is not accessible from any cell
and no cell is accessible from it.
(1, 1) - (2, 1)
(1, 2) - (2, 1)
(2, 2) - (2, 1)
(2, 1) - (1, 1)
(2, 1) - (1, 2)
(2, 1) - (2, 2)
Consider each cell as a node, numbered from 1 to N*N. Each cell (x, y) can be map to
number using (x – 1)*N + y. Now, consider each given allowed path as an edge between
nodes. This will form a disjoint set of the connected component. Now, using Depth First
Traversal or Breadth First Traversal, we can easily find the number of nodes or size of a
connected component, say x. Now, count of non-accessible paths are x*(N*N – x). This
way we can find non-accessible paths for each connected path.
1408
Chapter 201. Number of pair of positions in matrix which are not accessible
1409
Chapter 201. Number of pair of positions in matrix which are not accessible
}
return ans;
}
// Inserting the edge between edge.
void insertpath(vector<int> graph[], int N, int x1,
int y1, int x2, int y2)
{
// Mapping the cell coordinate into node number.
int a = (x1 - 1) * N + y1;
int b = (x2 - 1) * N + y2;
// Inserting the edge.
graph[a].push_back(b);
graph[b].push_back(a);
}
// Driven Program
int main()
{
int N = 2;
vector<int> graph[N*N + 1];
insertpath(graph, N, 1, 1, 1, 2);
insertpath(graph, N, 1, 2, 2, 2);
cout << countNonAccessible(graph, N) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-pair-positions-matrix-not-accessible/
1410
Chapter 202
We can solve this problem recursively, we start from two corners of a palindromic path(top-
left and bottom right). In each recursive call, we maintain a state which will constitute two
cells one from starting and one from end which should be equal for palindrome property. If
at a state, both cell characters are equal then we call recursively with all possible movements
in both directions.
1411
Chapter 202. Number of palindromic paths in a matrix
As this can lead to solving same subproblem multiple times, we have taken a map memo in
below code which stores the calculated result with key as indices of starting and ending cell
so if subproblem with same starting and ending cell is called again, result will be returned
by memo directly instead of recalculating again.
Please see below code for better understanding,
1412
Chapter 202. Number of palindromic paths in a matrix
// return 0
if (rs < 0 || rs >= R || cs < 0 || cs >= C)
return 0;
if (re < 0 || re < rs || ce < 0 || ce < cs)
return 0;
// Base case 2 : if values are not equal
// then palindrome property rs not satisfied,
// so return 0
if (mat[rs][cs] != mat[re][ce])
return 0;
// If we reach here, then matrix cells are same.
// Base Case 3 : if indices are adjacent then
// return 1
if (abs((rs - re) + (cs - ce)) <= 1)
return 1;
// if result rs precalculated, return from map
if (memo.find(cells(rs, cs, re, ce)) != memo.end())
return memo[cells(rs, cs, re, ce)];
int ret = 0; // Initialize result
// calling recursively for all possible movements
ret += getPalindromicPathsRecur(mat, rs + 1, cs,
re - 1, ce, memo);
ret += getPalindromicPathsRecur(mat, rs + 1, cs, re,
ce - 1, memo);
ret += getPalindromicPathsRecur(mat, rs, cs + 1,
re - 1, ce, memo);
ret += getPalindromicPathsRecur(mat, rs, cs + 1, re,
ce - 1, memo);
// storing the calculated result in map
memo[cells(rs, cs, re, ce)] = ret;
return ret;
}
// method returns number of palindromic paths in matrix
int getPalindromicPaths(char mat[R][C])
{
map<cells, int> memo;
return getPalindromicPathsRecur(mat, 0, 0, R - 1,
C - 1, memo);
}
1413
Chapter 202. Number of palindromic paths in a matrix
// Driver code to test above methods
int main()
{
char mat[R][C] =
{
'a', 'a', 'a', 'b',
'b', 'a', 'a', 'a',
'a', 'b', 'b', 'a'
};
printf("%d", getPalindromicPaths(mat));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-of-palindromic-paths-in-a-matrix/
1414
Chapter 203
Input: k = 12
mat[][] = { {1, 2, 3},
{4, 6, 5},
{3, 2, 1}
};
Output: 2
There are two paths with 12 coins
1 -> 2 -> 6 -> 2 -> 1
1 -> 2 -> 3 -> 5 -> 1
If (m == 0 and n == 0)
return 1 if mat[0][0] == k else return 0
Else:
pathCount(m, n, k) = pathCount(m-1, n, k - mat[m][n]) +
pathCount(m, n-1, k - mat[m][n])
1415
Chapter 203. Number of paths with exactly k coins
C++
// A Naive Recursive C++ program to count paths with exactly
// 'k' coins
#include <bits/stdc++.h>
#define R 3
#define C 3
using namespace std;
// Recursive function to count paths with sum k from
// (0, 0) to (m, n)
int pathCountRec(int mat[][C], int m, int n, int k)
{
// Base cases
if (m < 0 || n < 0) return 0;
if (m==0 && n==0) return (k == mat[m][n]);
// (m, n) can be reached either through (m-1, n) or
// through (m, n-1)
return pathCountRec(mat, m-1, n, k-mat[m][n]) +
pathCountRec(mat, m, n-1, k-mat[m][n]);
}
// A wrapper over pathCountRec()
int pathCount(int mat[][C], int k)
{
return pathCountRec(mat, R-1, C-1, k);
}
// Driver program
int main()
{
int k = 12;
int mat[R][C] = { {1, 2, 3},
{4, 6, 5},
{3, 2, 1}
};
cout << pathCount(mat, k);
return 0;
}
Python3
1416
Chapter 203. Number of paths with exactly k coins
PHP
<?php
// A Naive Recursive PHP program to
// count paths with exactly 'k' coins
$R = 3;
$C = 3;
// Recursive function to count paths
// with sum k from (0, 0) to (m, n)
function pathCountRec( $mat, $m, $n, $k)
{
1417
Chapter 203. Number of paths with exactly k coins
// Base cases
if ($m < 0 or $n < 0)
return 0;
if ($m == 0 and $n == 0)
return ($k == $mat[$m][$n]);
// (m, n) can be reached either
// through (m-1, n) or through
// (m, n-1)
return pathCountRec($mat, $m - 1,
$n, $k - $mat[$m][$n])
+ pathCountRec($mat, $m,
$n - 1, $k - $mat[$m][$n]);
}
// A wrapper over pathCountRec()
function pathCount($mat, $k)
{
global $R, $C;
return pathCountRec($mat, $R-1,
$C-1, $k);
}
// Driver program
$k = 12;
$mat = array(array(1, 2, 3),
array(4, 6, 5),
array(3, 2, 1) );
echo pathCount($mat, $k);
// This code is contributed by anuj_67.
?>
Output:
The time complexity of above solution recursive is exponential. We can solve this problem
in Pseudo Polynomial Time (time complexity is dependent on numeric value of input) using
Dynamic Programming. The idea is to use a 3 dimensional table dp[m][n][k] where m is row
number, n is column number and k is number of coins. Below is Dynamic Programming
based C++ implementation.
1418
Chapter 203. Number of paths with exactly k coins
Output:
1419
Chapter 203. Number of paths with exactly k coins
Source
https://www.geeksforgeeks.org/number-of-paths-with-exactly-k-coins/
1420
Chapter 204
Number of positions with Same address in row major and column major order - Geeks-
forGeeks
Given a 2D array of size M x N. Calculate count of positions in 2D array where address as
per row major order equals to address as per column major order.
Examples:
Input : 3 5
Output : 3
Row major address is same as column major for following i, j
pairs (1, 1), (2, 3) & (3, 5)
Input : 4 4
Output : 4
1421
Chapter 204. Number of positions with Same address in row major and column major
order
C++
1422
Chapter 204. Number of positions with Same address in row major and column major
order
// vertical 1D array
if (N == 1)
return M;
if (N > M) {
// iterating for all possible i
for (int i = 1; i <= M; i++) {
int numerator = N * i - N + M - i;
int denominator = M - 1;
// checking if j is integer
if (numerator % denominator == 0) {
int j = numerator / denominator;
// checking if j lies b/w 1 to N
if (j >= 1 && j <= N)
count++;
}
}
}
else {
// iterating for all possible j
for (int j = 1; j <= N; j++) {
int numerator = M * j - M + N - j;
int denominator = N - 1;
// checking if i is integer
if (numerator % denominator == 0) {
int i = numerator / denominator;
// checking if i lies b/w 1 to M
if (i >= 1 && i <= M)
count++;
}
}
}
return count;
}
// Driver Code
int main()
{
int M = 3, N = 5;
cout << getCount(M, N) << endl;
return 0;
1423
Chapter 204. Number of positions with Same address in row major and column major
order
Java
1424
Chapter 204. Number of positions with Same address in row major and column major
order
C#
1425
Chapter 204. Number of positions with Same address in row major and column major
order
PHP
<?php
// PHP Program to count the number
1426
Chapter 204. Number of positions with Same address in row major and column major
order
1427
Chapter 204. Number of positions with Same address in row major and column major
order
Output :
Source
https://www.geeksforgeeks.org/number-positions-address-row-major-column-major-order/
1428
Chapter 205
Operating System | Banker’s Algorithm : Print all the safe state (or safe sequences) -
GeeksforGeeks
Prerequisite – Resource Allocation Graph (RAG), Banker’s Algorithm, Program for Banker’s
Algorithm
Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algo-
rithm test for safety simulating the allocation for predetermined maximum possible amounts
of all resources, then makes an “s-state” check to test for possible activities, before deciding
whether allocation should be allowed to continue.
In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is
it safe to allocate a resource to a process and if not then resource is not allocated to that
process. Determining a safe sequence(even if there is only 1) will assure that system will
not go into deadlock.
Banker’s algorithm is generally used to find if a safe sequence exist or not. But here we will
determine the total number of safe sequences and print all safe sequences.
The data structure used are:
• Available vector
• Max Matrix
• Allocation Matrix
• Need Matrix
Example:
1429
Chapter 205. Operating System | Banker’s Algorithm : Print all the safe state (or safe
sequences)
Input :
Explanation –
Total resources are R1 = 10, R2 = 5, R3 = 7 and allocated resources are R1 = (0+2+3+2
=) 7, R2 = (1+0+0+1 =) 2, R3 = (0+0+2+1 =) 3. Therefore, remaining resources are R1
= (10 – 7 =) 3, R2 = (5 – 2 =) 3, R3 = (7 – 3 =) 4.
Remaining available = Total resources – allocated resources
and
Remaining need = max – allocated
So, we can start from either P2 or P4. We can not satisfy remaining need from available
resources of either P1 or P3 in first or second attempt step of Banker’s algorithm. There
are only four possible safe sequences. These are :
P2–> P4–> P1–> P3
P2–> P4–> P3–> P1
P4–> P2–> P1–> P3
P4–> P2–> P3–> P1
Code –
// CPP Program to Print all possible safe sequences using banker's algorithm
#include <iostream>
#include <string.h>
#include <vector>
// total number of process
#define P 4
// total number of resources
#define R 3
1430
Chapter 205. Operating System | Banker’s Algorithm : Print all the safe state (or safe
sequences)
// total safe-sequences
int total = 0;
using namespace std;
// function to check if process
// can be allocated or not
bool is_available(int process_id, int allocated[][R],
int max[][R], int need[][R], int available[])
{
bool flag = true;
// check if all the available resources
// are less greater than need of process
for (int i = 0; i < R; i++) {
if (need[process_id][i] > available[i])
flag = false;
}
return flag;
}
// Print all the safe-sequences
void safe_sequence(bool marked[], int allocated[][R], int max[][R],
int need[][R], int available[], vector<int> safe)
{
for (int i = 0; i < P; i++) {
// check if it is not marked
// already and can be allocated
if (!marked[i] && is_available(i, allocated, max, need, available)) {
// mark the process
marked[i] = true;
// increase the available
// by deallocating from process i
for (int j = 0; j < R; j++)
available[j] += allocated[i][j];
safe.push_back(i);
// find safe sequence by taking process i
safe_sequence(marked, allocated, max, need, available, safe);
safe.pop_back();
1431
Chapter 205. Operating System | Banker’s Algorithm : Print all the safe state (or safe
sequences)
1432
Chapter 205. Operating System | Banker’s Algorithm : Print all the safe state (or safe
sequences)
int sum = 0;
for (int j = 0; j < P; j++)
sum += allocated[j][i];
available[i] = resources[i] - sum;
}
// safe vector for displaying a safe-sequence
vector<int> safe;
// marked of size P for marking allocated process
bool marked[P];
memset(marked, false, sizeof(marked));
// need matrix of size P*R
int need[P][R];
for (int i = 0; i < P; i++)
for (int j = 0; j < R; j++)
need[i][j] = max[i][j] - allocated[i][j];
cout << "Safe sequences are:" << endl;
safe_sequence(marked, allocated, max, need, available, safe);
cout << "\nThere are total " << total << " safe-sequences" << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/operating-system-bankers-algorithm-print-safe-state-safe-sequences/
1433
Chapter 206
Pascal Matrix
The elements of the symmetric Pascal Matrix are the binomial coefficient, i.e
Given a positive integer n. The task is to print the Symmetric Pascal Matrix of size n x n.
Examples:
1434
Chapter 206. Pascal Matrix
Input : n = 5
Output :
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
C++
1435
Chapter 206. Pascal Matrix
// Driven Program
int main()
{
int n = 5;
printpascalmatrix(n);
return 0;
}
Java
1436
Chapter 206. Pascal Matrix
// Driven Program
public static void main (String[] args)
{
int n = 5;
printpascalmatrix(n);
}
}
// This code is contributed by vt_m.
Python3
1437
Chapter 206. Pascal Matrix
n = 5;
printpascalmatrix(n);
# This code is contributed by mits
C#
// C# program to print
// symmetric pascal matrix.
using System;
class GFG {
// Print Pascal Matrix
static void printpascalmatrix(int n)
{
int[, ] C = new int[2 * n + 1, 2 * n + 1];
// Calculate value of Binomial Coefficient
// in bottom up manner
for (int i = 0; i <= 2 * n; i++) {
for (int j = 0; j <= Math.Min(i, 2 * n); j++) {
// Base Cases
if (j == 0 || j == i)
C[i, j] = 1;
// Calculate value using previously
// stored values
else
C[i, j] = C[i - 1, j - 1]
+ C[i - 1, j];
}
}
// Printing the pascal matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
Console.Write(C[i + j, i] + " ");
Console.WriteLine();
}
}
// Driven Program
public static void Main()
{
int n = 5;
1438
Chapter 206. Pascal Matrix
printpascalmatrix(n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to print symmetric
// pascal matrix.
// Print Pascal Matrix
function printpascalmatrix($n)
{
$C[2 * $n + 1][2 * $n + 1] = (0);
// Calculate value of Binomial
// Coefficient in ottom up manner
for ($i = 0; $i <= 2 * $n; $i++)
{
for ($j = 0; $j <= min($i, 2 * $n); $j++)
{
// Base Cases
if ($j == 0 || $j == $i)
$C[$i][$j] = 1;
// Calculate value
// using previously
// stored values
else
$C[$i][$j] = $C[$i - 1][$j - 1] +
$C[$i - 1][$j];
}
}
// Printing the pascal matrix
for ($i = 0; $i < $n; $i++) {
for ( $j = 0; $j < $n; $j++)
echo $C[$i + $j][$i], " ";
echo "\n";
}
}
// Driver Code
$n = 5;
1439
Chapter 206. Pascal Matrix
printpascalmatrix($n);
// This code is contributed by aj_36
?>
Output:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
Source
https://www.geeksforgeeks.org/pascal-matrix/
1440
Chapter 207
One interesting observation is, the only allowed moves are down and right, we need N-1
down moves and N-1 right moves to reach destination (bottom rightmost). So any path
from from top left corner to bottom right corner requires 2N – 1 cells. In average value,
denominator is fixed and we need to just maximize numerator. Therefore we basically need
to to find maximum sum path. Calculating maximum sum of path is a classic dynamic
programming problem, if dp[i][j] represents maximum sum till cell (i, j) from (0, 0) then at
each cell (i, j), we update dp[i][j] as below,
1441
Chapter 207. Path with maximum average value
Once we get maximum sum of all paths we will divide this sum by (2N – 1) and we will get
our maximum average.
C++
1442
Chapter 207. Path with maximum average value
{7, 3, 9}
};
printf("%f", maxAverageOfPath(cost, 3));
return 0;
}
Java
1443
Chapter 207. Path with maximum average value
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
1444
Chapter 207. Path with maximum average value
Output:
1445
Chapter 207. Path with maximum average value
5.2
Source
https://www.geeksforgeeks.org/path-maximum-average-value/
1446
Chapter 208
Performance analysis of Row major and Column major order of storing arrays in C - Geeks-
forGeeks
In computing, row-major order and column-major order are methods for storing multidi-
mensional arrays in linear storage such as random access memory.
The two mentioned ways differ from each other with respect to the order in which elements
are stored contiguously in the memory. The elements in row-major order are arranged
consecutively along the row and that in the column-major order are arranged consecutively
along the column. While the terms allude to the rows and columns of a two-dimensional
array, i.e. a matrix, the orders can be generalized to arrays of any dimension by noting that
the terms row-major and column-major are equivalent to lexicographic and lexicographic
orders, respectively.
Below program illustrates that row major order storing of arrays in C is more efficient than
column-major order(though Pascal and Fortran follows column major order):
#include <stdio.h>
#include <time.h>
int m[9999][999];
void main()
{
int i, j;
clock_t start, stop;
double d = 0.0;
1447
Chapter 208. Performance analysis of Row major and Column major order of storing
arrays in C
start = clock();
for (i = 0; i < 9999; i++)
for (j = 0; j < 999; j++)
m[i][j] = m[i][j] + (m[i][j] * m[i][j]);
d = (double)(stop - start) / CLOCKS_PER_SEC;
printf("The run-time of row major order is %lf\n", d);
start = clock();
for (j = 0; j < 999; j++)
for (i = 0; i < 9999; i++)
m[i][j] = m[i][j] + (m[i][j] * m[i][j]);
stop = clock();
d = (double)(stop - start) / CLOCKS_PER_SEC;
printf("The run-time of column major order is %lf", d);
}
Output:
Source
https://www.geeksforgeeks.org/performance-analysis-of-row-major-and-column-major-order-of-storing-arrays-in-c/
1448
Chapter 209
Place N^2 numbers in matrix such that every row has an equal sum - GeeksforGeeks
Given a number N, place numbers from the range [1, N2 ] in an NxN matrix such that sum
in every row is equal.
Examples:
Input: N = 3
Output: 1 5 9
2 6 7
3 4 8
Sum in 1st row: 15
Sum in 2nd row: 15
Sum in 2nd row: 15
Input: N = 5
Output: 1 7 13 19 25
2 8 14 20 21
3 9 15 16 22
4 10 11 17 23
5 6 12 18 24
A Greedy Approach has been used to fill the matrix, where the insertion of elements in
the matrix is done row-wise. The required matrix can be obtained using below steps:
• Fill the matrix initially with numbers in the range [1, N2 ] using matrix traversal.
1449
Chapter 209. Place N^2 numbers in matrix such that every row has an equal sum
• Traverse the matrix and change every position in a new matrix considering it as answer
matrix by answer[i][j] = mat[j][(i+j)%n].
1450
Chapter 209. Place N^2 numbers in matrix such that every row has an equal sum
Output:
1 7 13 19 25
2 8 14 20 21
3 9 15 16 22
4 10 11 17 23
5 6 12 18 24
Source
https://www.geeksforgeeks.org/place-n2-numbers-in-matrix-such-that-every-row-has-an-equal-sum/
1451
Chapter 210
Examples:
1452
Chapter 210. Possible moves of knight
#define m 4
using namespace std;
// To calculate possible moves
int findPossibleMoves(int mat[n][m], int p, int q)
{
// All possible moves of a knight
int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
int count = 0;
// Check if each possible move is valid or not
for (int i = 0; i < 8; i++) {
// Position of knight after move
int x = p + X[i];
int y = q + Y[i];
// count valid moves
if (x >= 0 && y >= 0 && x < n && y < m
&& mat[x][y] == 0)
count++;
}
// Return number of possible moves
return count;
}
// Driver program to check findPossibleMoves()
int main()
{
int mat[n][m] = { { 1, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 0, 1 },
{ 0, 1, 1, 1 } };
int p = 2, q = 2;
cout << findPossibleMoves(mat, p, q);
return 0;
}
Java
1453
Chapter 210. Possible moves of knight
C#
1454
Chapter 210. Possible moves of knight
class GFG
{
static int n = 4;
static int m = 4;
// To calculate
// possible moves
static int findPossibleMoves(int [,]mat,
int p, int q)
{
// All possible moves
// of a knight
int []X = { 2, 1, -1, -2,
-2, -1, 1, 2 };
int []Y = { 1, 2, 2, 1,
-1, -2, -2, -1 };
int count = 0;
// Check if each possible
// move is valid or not
for (int i = 0; i < 8; i++)
{
// Position of knight
// after move
int x = p + X[i];
int y = q + Y[i];
// count valid moves
if (x >= 0 && y >= 0 &&
x < n && y < m &&
mat[x, y] == 0)
count++;
}
// Return number
// of possible moves
return count;
}
// Driver Code
static public void Main ()
{
int [,]mat = { { 1, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 0, 1 },
1455
Chapter 210. Possible moves of knight
{ 0, 1, 1, 1 }};
int p = 2, q = 2;
Console.WriteLine(findPossibleMoves(mat,
p, q));
}
}
// This code is contributed by m_kit
PHP
<?php
// PHP program to find number
// of possible moves of knight
$n = 4;
$m = 4;
// To calculate possible moves
function findPossibleMoves($mat,
$p, $q)
{
global $n;
global $m;
// All possible moves
// of a knight
$X = array(2, 1, -1, -2,
-2, -1, 1, 2);
$Y = array(1, 2, 2, 1,
-1, -2, -2, -1);
$count = 0;
// Check if each possible
// move is valid or not
for ($i = 0; $i < 8; $i++)
{
// Position of
// knight after move
$x = $p + $X[$i];
$y = $q + $Y[$i];
// count valid moves
if ($x >= 0 && $y >= 0 &&
$x < $n && $y < $m &&
1456
Chapter 210. Possible moves of knight
$mat[$x][$y] == 0)
$count++;
}
// Return number
// of possible moves
return $count;
}
// Driver Code
$mat = array(array(1, 0, 1, 0),
array(0, 1, 1, 1),
array(1, 1, 0, 1),
array(0, 1, 1, 1));
$p = 2; $q = 2;
echo findPossibleMoves($mat,
$p, $q);
// This code is contributed by ajit
?>
Output:
References:
https://en.wikipedia.org/wiki/Knight_(chess)
Improved By : jit_t
Source
https://www.geeksforgeeks.org/possible-moves-knight/
1457
Chapter 211
1458
Chapter 211. Prim’s Algorithm (Simple Implementation for Adjacency Matrix
Representation)
if (u == v)
return false;
if (inMST[u] == false && inMST[v] == false)
return false;
else if (inMST[u] == true && inMST[v] == true)
return false;
return true;
}
void primMST(int cost[][V])
{
vector<bool> inMST(V, false);
// Include first vertex in MST
inMST[0] = true;
// Keep adding edges while number of included
// edges does not become V-1.
int edge_count = 0, mincost = 0;
while (edge_count < V - 1) {
// Find minimum weight valid edge.
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (cost[i][j] < min) {
if (isValidEdge(i, j, inMST)) {
min = cost[i][j];
a = i;
b = j;
}
}
}
}
if (a != -1 && b != -1) {
printf("Edge %d:(%d, %d) cost: %d \n",
edge_count++, a, b, min);
mincost = mincost + min;
inMST[b] = inMST[a] = true;
}
}
printf("\n Minimum cost= %d \n", mincost);
}
// driver program to test above function
int main()
{
/* Let us create the following graph
1459
Chapter 211. Prim’s Algorithm (Simple Implementation for Adjacency Matrix
Representation)
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
int cost[][V] = {
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};
// Print the solution
primMST(cost);
return 0;
}
Output:
Minimum cost= 16
Source
https://www.geeksforgeeks.org/prims-algorithm-simple-implementation-for-adjacency-matrix-representation/
1460
Chapter 212
Input: mat[][] =
{{1, 2, 3, 4}
{5, 6, 7, 8}
{9, 10, 11, 12}
{13, 14, 15, 16}}
k = 6
Output: 12
Input: mat[][] =
{{1, 2, 3, 4, 5, 6}
{7, 8, 9, 10, 11, 12}
{13, 14, 15, 16, 17, 18}}
k = 17
Output: 10
Simple Solution:
One simple solution is to start traversing matrix in spiral form Print Spiral Matrix and
start a counter i.e; count = 0. Whenever count gets equal to K, print that element. Time
complexity for this approach will be O(n^2).
Efficient Solution:
We will consider only edge of the matrix at a time and then do recursion for the sub matrix
made by removing edges of main matrix.
1461
Chapter 212. Print K’th element in spiral form of matrix
1462
Chapter 212. Print K’th element in spiral form of matrix
int k = 17;
cout << findK(a, 3,6,k) << endl;
return 0;
}
Output:
10
Time Complexity : O(c) where c is number of outer circular rings with respect to k’th
element.
Space complexity: O(1)
Source
https://www.geeksforgeeks.org/print-kth-element-spiral-form-matrix/
1463
Chapter 213
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
1 7 13 14 15 16 17 18 12 6 5 4 3 2 8 9 10 11
Explanation :
1464
Chapter 213. Print a given matrix in counter-clock wise spiral form
C++
1465
Chapter 213. Print a given matrix in counter-clock wise spiral form
while (k < m && l < n)
{
if (cnt == total)
break;
// Print the first column
// from the remaining columns
for (i = k; i < m; ++i)
{
cout << arr[i][l] << " ";
cnt++;
}
l++;
if (cnt == total)
break;
// Print the last row from
// the remaining rows
for (i = l; i < n; ++i)
{
cout << arr[m - 1][i] << " ";
cnt++;
}
m--;
if (cnt == total)
break;
// Print the last column
// from the remaining columns
if (k < m)
{
for (i = m - 1; i >= k; --i)
{
cout << arr[i][n - 1] << " ";
cnt++;
}
n--;
}
if (cnt == total)
break;
// Print the first row
// from the remaining rows
if (l < n)
1466
Chapter 213. Print a given matrix in counter-clock wise spiral form
{
for (i = n - 1; i >= l; --i)
{
cout << arr[k][i] << " ";
cnt++;
}
k++;
}
}
}
// Driver Code
int main()
{
int arr[R][C] = {{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }};
counterClockspiralPrint(R, C, arr);
return 0;
}
Java
1467
Chapter 213. Print a given matrix in counter-clock wise spiral form
1468
Chapter 213. Print a given matrix in counter-clock wise spiral form
Python3
1469
Chapter 213. Print a given matrix in counter-clock wise spiral form
1470
Chapter 213. Print a given matrix in counter-clock wise spiral form
C#
// C# implementation to print
// the counter clock wise
// spiral traversal of matrix;
using System;
class GFG
{
static int R = 4;
static int C = 4;
// function to print the required traversal
static void counterClockspiralPrint(int m,
int n,
int[,] arr)
{
int i, k = 0, l = 0;
// k - starting row index
// m - ending row index
// l - starting column index
// n - ending column index
// i - iterator
// initialize the count
int cnt = 0;
// total number of elements in matrix
1471
Chapter 213. Print a given matrix in counter-clock wise spiral form
int total = m * n;
while (k < m && l < n)
{
if (cnt == total)
break;
// Print the first column from
// the remaining columns
for (i = k; i < m; ++i)
{
Console.Write(arr[i,l] + " ");
cnt++;
}
l++;
if (cnt == total)
break;
// Print the last row from
// the remaining rows
for (i = l; i < n; ++i)
{
Console.Write(arr[m - 1, i] + " ");
cnt++;
}
m--;
if (cnt == total)
break;
// Print the last column from
// the remaining columns
if (k < m) {
for (i = m - 1; i >= k; --i)
{
Console.Write(arr[i, n - 1] + " ");
cnt++;
}
n--;
}
if (cnt == total)
break;
// Print the first row from
// the remaining rows
if (l < n)
1472
Chapter 213. Print a given matrix in counter-clock wise spiral form
{
for (i = n - 1; i >= l; --i)
{
Console.Write(arr[k, i] + " ");
cnt++;
}
k++;
}
}
}
// Driver code
public static void Main()
{
int[,] arr =new int[,] {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
// Function calling
counterClockspiralPrint(R, C, arr);
}
}
// This code is contributed by KRV.
PHP
<?php
// PHP implementation to print
// the counter clock wise
// spiral traversal of matrix
$R = 4;
$C = 4;
// function to print
// the required traversal
function counterClockspiralPrint($m, $n,
$arr)
{
$i; $k = 0; $l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator */
1473
Chapter 213. Print a given matrix in counter-clock wise spiral form
// initialize the count
$cnt = 0;
// total number of
// elements in matrix
$total = $m * $n;
while ($k < $m and $l < $n)
{
if ($cnt == $total)
break;
// Print the first column
// from the remaining columns
for ($i = $k; $i < $m; ++$i)
{
echo $arr[$i][$l] ," ";
$cnt++;
}
$l++;
if ($cnt == $total)
break;
// Print the last row from
// the remaining rows
for ($i = $l; $i < $n; ++$i)
{
echo $arr[$m - 1][$i] , " ";
$cnt++;
}
$m--;
if ($cnt == $total)
break;
// Print the last column
// from the remaining columns
if ($k < $m)
{
for ($i = $m - 1; $i >= $k; --$i)
{
echo $arr[$i][$n - 1] , " ";
$cnt++;
}
$n--;
}
1474
Chapter 213. Print a given matrix in counter-clock wise spiral form
if ($cnt == $total)
break;
// Print the first row
// from the remaining rows
if ($l < $n) {
for ($i = $n - 1; $i >= $l; --$i)
{
echo $arr[$k][$i] , " ";
$cnt++;
}
$k++;
}
}
}
// Driver Code
global $R,$C;
$arr = array(array( 1, 2, 3, 4 ),
array( 5, 6, 7, 8 ),
array( 9, 10, 11, 12 ),
array( 13, 14, 15, 16 ));
echo counterClockspiralPrint($R, $C, $arr);
// This code is contributed by anuj_67.
?>
Output :
1 5 9 13 14 15 16 12 8 4 3 2 6 10 11 7
Source
https://www.geeksforgeeks.org/print-given-matrix-counter-clock-wise-spiral-form/
1475
Chapter 214
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
C++
1476
Chapter 214. Print a given matrix in reverse spiral form
// Function that print matrix in reverse spiral form.
void ReversespiralPrint(int m, int n, int a[R][C])
{
// Large array to initialize it
// with elements of matrix
long int b[100];
/* k - starting row index
l - starting column index*/
int i, k = 0, l = 0;
// Counter for single dimension array
//in which elements will be stored
int z = 0;
// Total elements in matrix
int size = m*n;
while (k < m && l < n)
{
// Variable to store value of matrix.
int val;
/* Print the first row from the remaining rows */
for (i = l; i < n; ++i)
{
// printf("%d ", a[k][i]);
val = a[k][i];
b[z] = val;
++z;
}
k++;
/* Print the last column from the remaining columns */
for (i = k; i < m; ++i)
{
// printf("%d ", a[i][n-1]);
val = a[i][n-1];
b[z] = val;
++z;
}
n--;
/* Print the last row from the remaining rows */
if ( k < m)
{
for (i = n-1; i >= l; --i)
1477
Chapter 214. Print a given matrix in reverse spiral form
{
// printf("%d ", a[m-1][i]);
val = a[m-1][i];
b[z] = val;
++z;
}
m--;
}
/* Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
{
// printf("%d ", a[i][l]);
val = a[i][l];
b[z] = val;
++z;
}
l++;
}
}
for (int i=size-1 ; i>=0 ; --i)
{
cout<<b[i]<<" ";
}
}
/* Driver program to test above functions */
int main()
{
int a[R][C] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}};
ReversespiralPrint(R, C, a);
return 0;
}
Java
1478
Chapter 214. Print a given matrix in reverse spiral form
int a[][])
{
// Large array to initialize it
// with elements of matrix
long b[] = new long[100];
/* k - starting row index
l - starting column index*/
int i, k = 0, l = 0;
// Counter for single dimension array
//in which elements will be stored
int z = 0;
// Total elements in matrix
int size = m * n;
while (k < m && l < n)
{
// Variable to store value of matrix.
int val;
/* Print the first row from the remaining
rows */
for (i = l; i < n; ++i)
{
val = a[k][i];
b[z] = val;
++z;
}
k++;
/* Print the last column from the remaining
columns */
for (i = k; i < m; ++i)
{
val = a[i][n-1];
b[z] = val;
++z;
}
n--;
/* Print the last row from the remaining
rows */
if ( k < m)
{
1479
Chapter 214. Print a given matrix in reverse spiral form
C#
1480
Chapter 214. Print a given matrix in reverse spiral form
using System;
class GFG {
public static int R = 3, C = 6;
// Function that print matrix in reverse spiral form.
public static void ReversespiralPrint(int m, int n,
int [,]a)
{
// Large array to initialize it
// with elements of matrix
long []b = new long[100];
/* k - starting row index
l - starting column index*/
int i, k = 0, l = 0;
// Counter for single dimension array
//in which elements will be stored
int z = 0;
// Total elements in matrix
int size = m * n;
while (k < m && l < n)
{
// Variable to store value of matrix.
int val;
/* Print the first row from the remaining
rows */
for (i = l; i < n; ++i)
{
val = a[k,i];
b[z] = val;
++z;
}
k++;
/* Print the last column from the remaining
columns */
for (i = k; i < m; ++i)
{
val = a[i,n-1];
b[z] = val;
++z;
1481
Chapter 214. Print a given matrix in reverse spiral form
}
n--;
/* Print the last row from the remaining
rows */
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
val = a[m-1,i];
b[z] = val;
++z;
}
m--;
}
/* Print the first column from the remaining
columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
{
val = a[i,l];
b[z] = val;
++z;
}
l++;
}
}
for (int x = size-1 ; x>=0 ; --x)
{
Console.Write(b[x]+" ");
}
}
/* Driver program to test above function */
public static void Main()
{
int [ ,]a = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}};
ReversespiralPrint(R, C, a);
}
1482
Chapter 214. Print a given matrix in reverse spiral form
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Code for Print a given
// matrix in reverse spiral form
$R=3;
$C=6;
// Function that print matrix
// in reverse spiral form.
function ReversespiralPrint($m, $n, array $a)
{
// Large array to initialize it
// with elements of matrix
$b;
// k - starting row index
// l - starting column index
$k = 0;
$l = 0;
// Counter for single dimension array
// in which elements will be stored
$z = 0;
// Total elements in matrix
$size = $m*$n;
while ($k < $m && $l < $n)
{
// Variable to store
// value of matrix.
$val;
// Print the first row from
// the remaining rows
for ($i = $l; $i < $n; ++$i)
{
$val = $a[$k][$i];
$b[$z] = $val;
++$z;
}
$k++;
1483
Chapter 214. Print a given matrix in reverse spiral form
// Print the last column from
// the remaining columns
for ($i = $k; $i < $m; ++$i)
{
// printf("%d ", a[i][n-1]);
$val = $a[$i][$n-1];
$b[$z] = $val;
++$z;
}
$n--;
// Print the last row from
// the remaining rows
if ( $k < $m)
{
for ($i = $n-1; $i >= $l; --$i)
{
// printf("%d ", a[m-1][i]);
$val = $a[$m-1][$i];
$b[$z] = $val;
++$z;
}
$m--;
}
// Print the first column
// from the remaining columns
if ($l < $n)
{
for ($i = $m - 1; $i >= $k; --$i)
{
$val = $a[$i][$l];
$b[$z] = $val;
++$z;
}
$l++;
}
}
for ($i = $size - 1; $i >= 0; --$i)
{
echo $b[$i]." ";
}
}
// Driver Code
1484
Chapter 214. Print a given matrix in reverse spiral form
Output:
11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1
Source
https://www.geeksforgeeks.org/print-given-matrix-reverse-spiral-form/
1485
Chapter 215
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
Input:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
1486
Chapter 215. Print a given matrix in spiral form
Solution:
C/C++
1487
Chapter 215. Print a given matrix in spiral form
1488
Chapter 215. Print a given matrix in spiral form
Java
1489
Chapter 215. Print a given matrix in spiral form
{
System.out.print(a[i][l]+" ");
}
l++;
}
}
}
// driver program
public static void main (String[] args)
{
int R = 3;
int C = 6;
int a[][] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}
};
spiralPrint(R,C,a);
}
}
// Contributed by Pramod Kumar
Python3
1490
Chapter 215. Print a given matrix in spiral form
for i in range(k, m) :
print(a[i][n - 1], end = " ")
n -= 1
# Print the last row from
# the remaining rows
if ( k < m) :
for i in range(n - 1, (l - 1), -1) :
print(a[m - 1][i], end = " ")
m -= 1
# Print the first column from
# the remaining columns
if (l < n) :
for i in range(m - 1, k - 1, -1) :
print(a[i][l], end = " ")
l += 1
# Driver Code
a = [ [1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18] ]
R = 3; C = 6
spiralPrint(R, C, a)
# This code is contributed by Nikita Tiwari.
C#
1491
Chapter 215. Print a given matrix in spiral form
i - iterator
*/
while (k < m && l < n)
{
// Print the first row from the remaining rows
for (i = l; i < n; ++i)
{
Console.Write(a[k, i] +" ");
}
k++;
// Print the last column from the remaining columns
for (i = k; i < m; ++i)
{
Console.Write(a[i,n - 1]+" ");
}
n--;
// Print the last row from the remaining rows */
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
Console.Write(a[m - 1, i]+" ");
}
m--;
}
// Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
{
Console.Write(a[i, l] + " ");
}
l++;
}
}
}
// Driver program
public static void Main ()
{
int R = 3;
int C = 6;
int [,]a = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
1492
Chapter 215. Print a given matrix in spiral form
PHP
<?php
// PHP program to print a given
// matrix in spiral form
$R = 3;
$C = 6;
function spiralPrint($m, $n, &$a)
{
$k = 0;
$l = 0;
/* $k - starting row index
$m - ending row index
$l - starting column index
$n - ending column index
$i - iterator
*/
while ($k < $m && $l < $n)
{
/* Print the first row from
the remaining rows */
for ($i = $l; $i < $n; ++$i)
{
echo $a[$k][$i] . " ";
}
$k++;
/* Print the last column
from the remaining columns */
for ($i = $k; $i < $m; ++$i)
{
echo $a[$i][$n - 1] . " ";
}
$n--;
/* Print the last row from
the remaining rows */
1493
Chapter 215. Print a given matrix in spiral form
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
Improved By : ChitraNayal
1494
Chapter 215. Print a given matrix in spiral form
Source
https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
1495
Chapter 216
Input :
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
Output :
1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
Input :
10 24 32
50 6 17
99 10 11
Output :
10 24 32 17 6 50 99 10 11
1496
Chapter 216. Print a given matrix in zigzag form
C++
1497
Chapter 216. Print a given matrix in zigzag form
Java
1498
Chapter 216. Print a given matrix in zigzag form
Python 3
1499
Chapter 216. Print a given matrix in zigzag form
# oddRow will be printed in
# the opposite direction
print(str(a[oddRow][i]),
end = " ")
# Skipping next row so as
# to get the next oddRow
oddRow = oddRow + 2
# Driver Code
r = 3
c = 5
mat = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]];
printZigZag(r , c , mat)
# This code is contributed
# by ChitraNayal
C#
1500
Chapter 216. Print a given matrix in zigzag form
PHP
<?php
// PHP program to print
// matrix in zig-zag form
// Method to print matrix
// in zig-zag form
function printZigZag($row, $col, $a)
{
//starts from the first row
1501
Chapter 216. Print a given matrix in zigzag form
$evenRow = 0;
//starts from the next row
$oddRow = 1;
while ($evenRow < $row)
{
for ( $i = 0; $i < $col; $i++)
{
// evenRow will be printed
// in the same direction
echo $a[$evenRow][$i], " ";
}
// Skipping next row so as
// to get the next evenRow
$evenRow = $evenRow + 2;
if($oddRow < $row)
{
for ($i = $col - 1; $i >= 0; $i--)
{
// oddRow will be printed in
// the opposite direction
echo $a[$oddRow][$i], " ";
}
}
// Skipping next row so as
// to get the next oddRow
$oddRow = $oddRow + 2;
}
}
// Driver Code
$r = 3; $c = 5;
$mat = array(array(1, 2, 3, 4, 5),
array(6, 7, 8, 9, 10),
array(11, 12, 13, 14, 15));
printZigZag($r , $c , $mat);
// This code is contributed by m_kit.
?>
Output :
1502
Chapter 216. Print a given matrix in zigzag form
1 2 3 4 5 10 9 8 7 6 11 12 13 14 15
Source
https://www.geeksforgeeks.org/print-given-matrix-zigzag-form/
1503
Chapter 217
Input : 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output : 4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1
Input : 1 9 4 10
3 6 90 11
2 30 85 72
6 31 99 15
Output : 10 11 72 15 99 85 90 4 9 6 30 31 6 2 3 1
Approach :To get the reverse wave form for a given matrix, we first print the elements of
the last column of the matrix in downward direction then print the elements of the 2nd last
column in the upward direction, then print the elements in third last column in downward
direction and so on. For example 1, the flow goes like :
1504
Chapter 217. Print a matrix in Reverse Wave Form
C++
1505
Chapter 217. Print a matrix in Reverse Wave Form
Java
1506
Chapter 217. Print a matrix in Reverse Wave Form
// m- Ending row index
//n - Ending column index
//i, j - Iterator
//wave - for Direction
//wave = 1 - Wave direction down
//wave = 0 - Wave direction up */
while (j >= 0)
{
// Check whether to go in
// upward or downward
if (wave == 1)
{
// Print the element of the matrix
// downward since the value of wave = 1
for (i = 0; i < m; i++)
System.out.print(arr[i][j] +" ");
wave = 0;
j--;
}
else {
// Print the elements of the
// matrix upward since the value
// of wave = 0
for (i = m - 1; i >= 0; i--)
System.out.print( arr[i][j] + " ");
wave = 1;
j--;
}
}
}
// Driver function
public static void main (String[] args)
{
int arr[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
WavePrint(R, C, arr);
}
}
1507
Chapter 217. Print a matrix in Reverse Wave Form
Python3
1508
Chapter 217. Print a matrix in Reverse Wave Form
arr = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ] ]
wavePrint(R, C, arr)
# This code is contributed by
# Upendra Singh Bartwal
C#
// C# implementation to print
// reverse wave form of matrix
using System;
class GFG {
static int R = 4;
static int C = 4;
// function to print reverse wave
// form for a given matrix
static void WavePrint(int m, int n, int [,]arr)
{
int i, j = n - 1, wave = 1;
// m- Ending row index
// n - Ending column index
// i, j - Iterator
// wave - for Direction
// wave = 1 - Wave direction down
// wave = 0 - Wave direction up */
while (j >= 0)
{
// Check whether to go in
// upward or downward
if (wave == 1) {
// Print the element of the
// matrix downward since the
// value of wave = 1
for (i = 0; i < m; i++)
Console.Write(arr[i,j] + " ");
wave = 0;
1509
Chapter 217. Print a matrix in Reverse Wave Form
j--;
}
else {
// Print the elements of the
// matrix upward since the value
// of wave = 0
for (i = m - 1; i >= 0; i--)
Console.Write( arr[i,j] + " ");
wave = 1;
j--;
}
}
}
// Driver function
public static void Main ()
{
int [,]arr = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
WavePrint(R, C, arr);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP implementation to print
// reverse wave form of matrix
$R = 4;
$C = 4;
// function to print reverse
// wave form for a given matrix
function WavePrint($m, $n, $arr)
{
global $R;
global $C;
$i; $j = $n - 1; $wave = 1;
1510
Chapter 217. Print a matrix in Reverse Wave Form
/* m - Ending row index
n - Ending column index
i, j - Iterator
wave - for Direction
wave = 1 - Wave direction down
wave = 0 - Wave direction up */
while ($j >= 0)
{
// Check whether to go in
// upward or downward
if ($wave == 1)
{
// Print the element of the
// matrix downward since the
// value of wave = 1
for ($i = 0; $i < $m; $i++)
echo $arr[$i][$j] , " ";
$wave = 0;
$j--;
}
else
{
// Print the elements of
// the matrix upward since
// the value of wave = 0
for ($i = $m - 1; $i >= 0; $i--)
echo $arr[$i][$j] , " ";
$wave = 1;
$j--;
}
}
}
// Driver Code
$arr = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 10, 11, 12),
array(13, 14, 15, 16));
WavePrint($R, $C, $arr);
// This code is contributed by ajit
?>
1511
Chapter 217. Print a matrix in Reverse Wave Form
Output:
4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1
Improved By : jit_t
Source
https://www.geeksforgeeks.org/print-matrix-reverse-wave-form/
1512
Chapter 218
1513
Chapter 218. Print a matrix in a spiral form starting from a point
int i, a = 0, b = 2;
int low_row = (0 > a) ? 0 : a;
int low_column = (0 > b) ? 0 : b - 1;
int high_row = ((a + 1) >= r) ? r - 1 : a + 1;
int high_column = ((b + 1) >= c) ? c - 1 : b + 1;
while ((low_row > 0 - r && low_column > 0 - c)) {
for (i = low_column + 1; i <= high_column &&
i < c && low_row >= 0; ++i)
cout << mat[low_row][i] << " ";
low_row -= 1;
for (i = low_row + 2; i <= high_row && i < r &&
high_column < c; ++i)
cout << mat[i][high_column] << " ";
high_column += 1;
for (i = high_column - 2; i >= low_column &&
i >= 0 && high_row < r; --i)
cout << mat[high_row][i] << " ";
high_row += 1;
for (i = high_row - 2; i > low_row && i >= 0
&& low_column >= 0; --i)
cout << mat[i][low_column] << " ";
low_column -= 1;
}
cout << endl;
}
// Driver code
int main()
{
int mat[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int r = 3, c = 3;
printSpiral(mat, r, c);
}
Java
1514
Chapter 218. Print a matrix in a spiral form starting from a point
static void printSpiral(int [][]mat, int r, int c)
{
int i, a = 0, b = 2;
int low_row = (0 > a) ? 0 : a;
int low_column = (0 > b) ? 0 : b - 1;
int high_row = ((a + 1) >= r) ? r - 1 : a + 1;
int high_column = ((b + 1) >= c) ? c - 1 : b + 1;
while ((low_row > 0 - r && low_column > 0 - c))
{
for (i = low_column + 1; i <= high_column &&
i < c && low_row >= 0; ++i)
System.out.print (mat[low_row][i] + " ");
low_row -= 1;
for (i = low_row + 2; i <= high_row && i < r &&
high_column < c; ++i)
System.out.print(mat[i][high_column] + " ");
high_column += 1;
for (i = high_column - 2; i >= low_column &&
i >= 0 && high_row < r; --i)
System.out.print(mat[high_row][i] + " ");
high_row += 1;
for (i = high_row - 2; i > low_row && i >= 0
&& low_column >= 0; --i)
System.out.print(mat[i][low_column] +" ");
low_column -= 1;
}
System.out.println();
}
// Driver code
static public void main (String[] args)
{
int [][]mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int r = 3, c = 3;
// Function calling
printSpiral(mat, r, c);
}
}
1515
Chapter 218. Print a matrix in a spiral form starting from a point
C#
// C# program to print a
// matrix in spiral form
using System;
class GFG {
static void printSpiral(int [,]mat, int r, int c)
{
int i, a = 0, b = 2;
int low_row = (0 > a) ? 0 : a;
int low_column = (0 > b) ? 0 : b - 1;
int high_row = ((a + 1) >= r) ? r - 1 : a + 1;
int high_column = ((b + 1) >= c) ? c - 1 : b + 1;
while ((low_row > 0 - r && low_column > 0 - c))
{
for (i = low_column + 1; i <= high_column &&
i < c && low_row >= 0; ++i)
Console.Write (mat[low_row,i] + " ");
low_row -= 1;
for (i = low_row + 2; i <= high_row && i < r &&
high_column < c; ++i)
Console.Write(mat[i,high_column] + " ");
high_column += 1;
for (i = high_column - 2; i >= low_column &&
i >= 0 && high_row < r; --i)
Console.Write(mat[high_row,i] + " ");
high_row += 1;
for (i = high_row - 2; i > low_row && i >= 0
&& low_column >= 0; --i)
Console.Write(mat[i,low_column] +" ");
low_column -= 1;
}
Console.WriteLine();
}
// Driver code
static public void Main ()
{
int [,]mat = {{1, 2, 3},
1516
Chapter 218. Print a matrix in a spiral form starting from a point
{4, 5, 6},
{7, 8, 9}};
int r = 3, c = 3;
// Function calling
printSpiral(mat, r, c);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to print a
// matrix in spiral form.
$MAX = 100;
function printSpiral($mat,
$r, $c)
{
global $MAX;
$i; $a = 0; $b = 2;
$low_row = (0 > $a) ?
0 : $a;
$low_column = (0 > $b) ?
0 : $b - 1;
$high_row = (($a + 1) >= $r) ?
$r - 1 : $a + 1;
$high_column = (($b + 1) >= $c) ?
$c - 1 : $b + 1;
while (($low_row > 0 - $r &&
$low_column > 0 - $c))
{
for ($i = $low_column + 1;
$i <= $high_column &&
$i < $c && $low_row >= 0; ++$i)
echo $mat[$low_row][$i], " ";
$low_row -= 1;
for ($i = $low_row + 2;
$i <= $high_row && $i < $r &&
$high_column < $c; ++$i)
echo $mat[$i][$high_column] , " ";
$high_column += 1;
1517
Chapter 218. Print a matrix in a spiral form starting from a point
for ($i = $high_column - 2;
$i >= $low_column &&
$i >= 0 && $high_row < $r; --$i)
echo $mat[$high_row][$i] , " ";
$high_row += 1;
for ($i = $high_row - 2;
$i > $low_row && $i >= 0 &&
$low_column >= 0; --$i)
echo $mat[$i][$low_column] , " ";
$low_column -= 1;
}
echo "\n";
}
// Driver code
$mat = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
$r = 3; $c = 3;
printSpiral($mat, $r, $c);
// This code is contributed by aj_36
?>
Output:
3 6 5 2 9 8 7 4 1
Source
https://www.geeksforgeeks.org/print-matrix-spiral-form-starting-point/
1518
Chapter 219
Print a matrix in alternate manner (left to right then right to left) - GeeksforGeeks
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to
right, then from right to left, and so on).
Examples:
Input :arr[][3] = { { 7 , 2 , 3 },
{ 2 , 3 , 4 },
{ 5 , 6 , 1 }};
Output : 7 2 3 4 3 2 5 6 1
The solution of this problem is that run two loops and and print row in left to right and
right to left manners. We maintain a flag to see if current row should be printed from left
to right or right to left. We toggle the flag after every iteration.
C++
1519
Chapter 219. Print a matrix in alternate manner (left to right then right to left)
#define C 3
// Function for print matrix in alternate manner
void convert(int arr[R][C])
{
bool leftToRight = true;
for (int i=0; i<R; i++)
{
if (leftToRight)
{
for (int j=0; j<C; j++)
printf("%d ", arr[i][j]);
}
else
{
for (int j=C-1; j>=0; j--)
printf("%d ",arr[i][j]);
}
leftToRight = !leftToRight;
}
}
// Driver code
int main()
{
int arr[][C] =
{
{ 1 , 2 , 3 },
{ 3 , 2 , 1 },
{ 4 , 5 , 6 },
};
convert(arr);
return 0;
}
PHP
<?php
// PHP program to print matrix
// in alternate manner
$R = 3;
$C = 3;
// Function for print matrix
// in alternate manner
function convert($arr)
1520
Chapter 219. Print a matrix in alternate manner (left to right then right to left)
{
global $R;
global $C;
$leftToRight = true;
for ($i = 0; $i < $R; $i++)
{
if ($leftToRight)
{
for ($j = 0; $j < $C; $j++)
echo $arr[$i][$j], " ";
}
else
{
for ($j = $C - 1; $j >= 0; $j--)
echo $arr[$i][$j], " ";
}
$leftToRight = !$leftToRight;
}
}
// Driver code
$arr = array(array(1 , 2 , 3 ),
array(3 , 2 , 1 ),
array(4 , 5 , 6 ));
convert($arr);
// This code is contributed by ajit
?>
Output:
1 2 3 1 2 3 4 5 6
Source
https://www.geeksforgeeks.org/print-matrix-alternate-manner-left-right-right-left/
1521
Chapter 220
Print all elements in sorted order from row and column wise sorted matrix - GeeksforGeeks
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print
all elements of matrix in sorted order.
Example:
Output:
Elements of matrix in sorted order
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
We can use Young Tableau to solve the above problem. The idea is to consider given 2D
array as Young Tableau and call extract minimum O(N)
// A C++ program to Print all elements in sorted order from row and
// column wise sorted matrix
#include<iostream>
#include<climits>
using namespace std;
1522
Chapter 220. Print all elements in sorted order from row and column wise sorted matrix
1523
Chapter 220. Print all elements in sorted order from row and column wise sorted matrix
// driver program to test above function
int main()
{
int mat[N][N] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};
printSorted(mat);
return 0;
}
Output:
Time complexity of extract minimum is O(N) and it is called O(N2 ) times. Therefore the
overall time complexity is O(N3 ).
A better solution is to use the approach used for merging k sorted arrays. The idea is to
use a Min Heap of size N which stores elements of first column. The do extract minimum.
In extract minimum, replace the minimum element with the next element of the row from
which the element is extracted. Time complexity of this solution is O(N2 LogN).
// C++ program to merge k sorted arrays of size n each.
#include<iostream>
#include<climits>
using namespace std;
#define N 4
// A min heap node
struct MinHeapNode
{
int element; // The element to be stored
int i; // index of the row from which the element is taken
int j; // index of the next element to be picked from row
};
// Prototype of a utility function to swap two min heap nodes
void swap(MinHeapNode *x, MinHeapNode *y);
// A class for Min Heap
class MinHeap
1524
Chapter 220. Print all elements in sorted order from row and column wise sorted matrix
{
MinHeapNode *harr; // pointer to array of elements in heap
int heap_size; // size of min heap
public:
// Constructor: creates a min heap of given size
MinHeap(MinHeapNode a[], int size);
// to heapify a subtree with root at given index
void MinHeapify(int );
// to get index of left child of node at index i
int left(int i) { return (2*i + 1); }
// to get index of right child of node at index i
int right(int i) { return (2*i + 2); }
// to get the root
MinHeapNode getMin() { return harr[0]; }
// to replace root with new node x and heapify() new root
void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); }
};
// This function prints elements of a given matrix in non-decreasing
// order. It assumes that ma[][] is sorted row wise sorted.
void printSorted(int mat[][N])
{
// Create a min heap with k heap nodes. Every heap node
// has first element of an array
MinHeapNode *harr = new MinHeapNode[N];
for (int i = 0; i < N; i++)
{
harr[i].element = mat[i][0]; // Store the first element
harr[i].i = i; // index of row
harr[i].j = 1; // Index of next element to be stored from row
}
MinHeap hp(harr, N); // Create the min heap
// Now one by one get the minimum element from min
// heap and replace it with next element of its array
for (int count = 0; count < N*N; count++)
{
// Get the minimum element and store it in output
MinHeapNode root = hp.getMin();
cout << root.element << " ";
// Find the next elelement that will replace current
1525
Chapter 220. Print all elements in sorted order from row and column wise sorted matrix
1526
Chapter 220. Print all elements in sorted order from row and column wise sorted matrix
Output:
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
Exercise:
Above solutions work for a square matrix. Extend the above solutions to work for an M*N
rectangular matrix.
This article is contributed by Varun. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/print-elements-sorted-order-row-column-wise-sorted-matrix/
1527
Chapter 221
Examples:
1528
Chapter 221. Print all n digit patterns formed by mobile Keypad
Input : N = 3
Output : all 3 digit Pattern are :
123, 125, 145, 147
236, 214, 258, 256, 254
321, 325, 369, 365
412, 456, 452, 458, 478
and so on ..
idea of this solution is based on the DFS. We pick all keypad key as a starting digit for
N_digit number one by one, after that we are try to generate all N digit pattern formed
by this key( Using DFS because we can only move either up, left, right or down from that
key).
1529
Chapter 221. Print all n digit patterns formed by mobile Keypad
{
// add current number to string
pattern.push_back((Keypad[x][y] + '0'));
// print pattern
if (pattern.size() == n) {
cout << pattern << " ";
return;
}
// These arrays are used to get row and
// column
// numbers of 4 neighbours of a given cell
static int row[] = { 0, 1, 0, -1 };
static int col[] = { 1, 0, -1, 0 };
// Mark this cell as visited
visited[x][y] = true;
// Recur for all connected neighbours
for (int k = 0; k < 4; k++)
if (isSafe(x + row[k], y + col[k], visited)
&& Keypad[x + row[k]][y + col[k]] != -1)
DFS(visited, Keypad, n, pattern,
x + row[k], y + col[k]);
// unvisited
visited[x][y] = false;
pattern.pop_back();
}
void patternOfSizeK(int Keypad[][3], int n)
{
// Make a bool array to mark visited cells.
// Initially all cells are unvisited
bool visited[4][3];
memset(visited, false, sizeof(visited));
// try to generate all pattern of size n
// by making every key of keypad as
// starting char of pattern
for (int i = 0; i < 4; i++)
for (int j = 0; j < 3; j++)
if (Keypad[i][j] != -1)
DFS(visited, Keypad, n, "", i, j);
}
1530
Chapter 221. Print all n digit patterns formed by mobile Keypad
Output:
123 125 145 147 236 256 258 254 214 369 365 325 321
456 458 452 478 412 569 563 589 580 587 547 541 523 521
698 658 654 652 632 789 780 785 745 741 896 874 856 854 852
980 987 985 965 963 089 087 085
Source
https://www.geeksforgeeks.org/print-n-digit-patterns-formed-mobile-keypad/
1531
Chapter 222
Print all palindromic paths from top left to bottom right in a matrix - GeeksforGeeks
Given a matrix containing lower alphabetical characters only, we need to print all palin-
dromic paths in given matrix. A path is defined as a sequence of cells starting from top-left
cell and ending at bottom-right cell. We are allowed to move to right and down only from
current cell. We cannot go down diagonally.
Explanation :
aaaaaa (0, 0) -> (0, 1) -> (1, 1) ->
(1, 2) -> (1, 3) -> (2, 3)
aaaaaa (0, 0) -> (0, 1) -> (0, 2) ->
(1, 2) -> (1, 3) -> (2, 3)
abaaba (0, 0) -> (1, 0) -> (1, 1) ->
(1, 2) -> (2, 2) -> (2, 3)
1532
Chapter 222. Print all palindromic paths from top left to bottom right in a matrix
Output :
1533
Chapter 222. Print all palindromic paths from top left to bottom right in a matrix
abaaba
aaaaaa
aaaaaa
Source
https://www.geeksforgeeks.org/print-palindromic-paths-top-left-bottom-right-matrix/
1534
Chapter 223
Print all possible paths from top left to bottom right of a mXn matrix - GeeksforGeeks
The problem is to print all the possible paths from top left to bottom right of a mXn matrix
with the constraints that from each cell you can either move only to right or down.
Examples :
Input : 1 2 3
4 5 6
Output : 1 4 5 6
1 2 5 6
1 2 3 6
Input : 1 2
3 4
Output : 1 2 4
1 3 4
The algorithm is a simple recursive algorithm, from each cell first print all paths by going
down and then print all paths by going right. Do this recursively for each cell encountered.
Following is C++ implementation of the above algorithm.
1535
Chapter 223. Print all possible paths from top left to bottom right of a mXn matrix
1536
Chapter 223. Print all possible paths from top left to bottom right of a mXn matrix
Output:
1 4 5 6
1 2 5 6
1 2 3 6
Note that in the above code, the last line of printAllPathsUtil() is commented, If we un-
comment this line, we get all the paths from the top left to bottom right of a nXm matrix
if the diagonal movements are also allowed. And also if moving to some of the cells are not
permitted then the same code can be improved by passing the restriction array to the above
function and that is left as an exercise.
This article is contributed by Hariprasad NG. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Python implementation
1537
Chapter 223. Print all possible paths from top left to bottom right of a mXn matrix
print(path)
allPaths.append(path)
return
# if we reach to the right most corner, we can only move down
if j == n-1:
for k in range(i,m):
path[indx+k-i] = maze[k][j]
#path.append(maze[j][k])
# if we hit this block, it means one path is completed.
# Add it to paths list and print
print(path)
allPaths.append(path)
return
# add current element to the path list
#path.append(maze[i][j])
path[indx] = maze[i][j]
# move down in y direction and call findPathsUtil recursively
findPathsUtil(maze, m, n, i+1, j, path, indx+1)
# move down in y direction and call findPathsUtil recursively
findPathsUtil(maze, m, n, i, j+1, path, indx+1)
if __name__ == '__main__':
maze = [[1,2,3],
[4,5,6],
[7,8,9]]
findPaths(maze,3,3)
#print(allPaths)
Output:
[1, 4, 7, 8, 9]
[1, 4, 5, 8, 9]
[1, 4, 5, 6, 9]
[1, 2, 5, 8, 9]
[1, 2, 5, 6, 9]
[1, 2, 3, 6, 9]
Improved By : ashritkumar
Source
https://www.geeksforgeeks.org/print-all-possible-paths-from-top-left-to-bottom-right-of-a-mxn-matrix/
1538
Chapter 224
1539
Chapter 224. Print cells with same rectangular sums in a matrix
1540
Chapter 224. Print cells with same rectangular sums in a matrix
1541
Chapter 224. Print cells with same rectangular sums in a matrix
mat[i][j];
if (totalSum == 2 * mainDiagRectangleSum)
cout << "(" << i << ", " << j << ")" << endl;
}
}
}
// Driver code to test above methods
int main()
{
int mat[R][C] =
{
1, 2, 3, 5,
4, 1, 0, 2,
0, 1, 2, 0,
7, 1, 1, 0
};
printCellWithSameRectangularArea(mat, R, C);
return 0;
}
Java
1542
Chapter 224. Print cells with same rectangular sums in a matrix
1543
Chapter 224. Print cells with same rectangular sums in a matrix
System.out.println();
}
System.out.println(); */
/* print all those indices at which sum of prime diagonal
rectangles is half of the total sum of matrix */
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int mainDiagRectangleSum = sum[i][j] +
sumr[i][j] - mat[i][j];
if (totalSum == 2 * mainDiagRectangleSum)
System.out.println("(" + i + ", " + j + ")");
}
}
}
// Driver code
public static void main(String[] args)
{
int mat[][] = {{1, 2, 3, 5},
{4, 1, 0, 2},
{0, 1, 2, 0},
{7, 1, 1, 0}};
printCellWithSameRectangularArea(mat, R, C);
}
}
// This code is contributed by Anant Agarwal.
Python
1544
Chapter 224. Print cells with same rectangular sums in a matrix
totalSum = 0
for i in range(m):
for j in range(n):
sumr[i][j] = sum[i][j] = mat[i][j];
totalSum += mat[i][j]
# updating first and last row separately
for i in range(1,m):
sum[i][0] += sum[i-1][0]
sumr[m-i-1][n-1] += sumr[m-i][n-1]
# updating first and last column separately
for j in range(1,n):
sum[0][j] += sum[0][j-1];
sumr[m-1][n-j-1] += sumr[m-1][n-j]
# updating sum and sumr indices by nearby indices
for i in range(1,m):
for j in range(1,n):
sum[i][j] += sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]
sumr[m-i-1][n-j-1] += sumr[m-i][n-j-1] + sumr[m-i-1][n-j] - sumr[m-i][n-j]
# Uncomment below code to print sum and reverse sum
# matrix
# print all those indices at which sum of prime diagonal
# rectangles is half of the total sum of matrix
for i in range(m):
for j in range(n):
mainDiagRectangleSum = sum[i][j] + sumr[i][j] - mat[i][j]
if (totalSum == 2 * mainDiagRectangleSum):
print "(",
print i,
print ",",
print j,
print ")",
# Driver code to test above methods
mat =[[1, 2, 3, 5,],
[4, 1, 0, 2,],
[0, 1, 2, 0],
[7, 1, 1, 0]]
printCellWithSameRectangularArea(mat, 4, 4)
# Contributed by Afzal
C#
1545
Chapter 224. Print cells with same rectangular sums in a matrix
1546
Chapter 224. Print cells with same rectangular sums in a matrix
1547
Chapter 224. Print cells with same rectangular sums in a matrix
{4, 1, 0, 2},
{0, 1, 2, 0},
{7, 1, 1, 0}};
printCellWithSameRectangularArea(mat, R, C);
}
}
// This code is contributed by vt_m.
Output:
(1, 1)
(2, 2)
Improved By : vt_m
Source
https://www.geeksforgeeks.org/print-cells-rectangular-sum-matrix/
1548
Chapter 225
Input : n = 4
Output :
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
Input : n = 3
Output :
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
1549
Chapter 225. Print concentric rectangular pattern in a 2d matrix
For the given n, the number of rows or columns to be printed will be 2*n – 1. We will print
the matrix in two parts. We will first print upper half from rows from 0 to floor((2*n – 1)/2)
and then second half from floor((2*n – 1)/2) + 1 to 2*n – 2.
Now for each row, we will print it in three parts. First part is decreasing sequence which
will start from n and decrease by 1 in each iteration. The number of iteration will be equal
to row number, the second part is a constant sequence where constant is n – i and it will be
print 2*n – 1 – 2 * row number, and the third part is increasing sequence which is nothing
but opposite of the first sequence.
For lower half, observe, it is a mirror image of upper half (excluding middle row). So, simply
run a loop of the upper half from (2*n – 1)/2 to 0.
Below is the basic implementation of this approach:
C++
1550
Chapter 225. Print concentric rectangular pattern in a 2d matrix
cout << endl;
}
// Lower Half
for (int i = s / 2 - 1; i >= 0; i--) {
// Decreasing Part
int m = n;
for (int j = 0; j < i; j++) {
cout << m << " ";
m--;
}
// Constant Part.
for (int k = 0; k < s - 2 * i; k++) {
cout << n - i << " ";
}
// Decreasing Part
m = n - i + 1;
for (int l = 0; l < i; l++) {
cout << m << " ";
m++;
}
cout << endl;
}
}
// Driven Program
int main()
{
int n = 3;
printPattern(n);
return 0;
}
Java
1551
Chapter 225. Print concentric rectangular pattern in a 2d matrix
1552
Chapter 225. Print concentric rectangular pattern in a 2d matrix
}
// Constant Part.
for (int k = 0;
k < s - 2 * i; k++)
{
System.out.print(n - i + " ");
}
// Decreasing Part
m = n - i + 1;
for (int l = 0; l < i; l++)
{
System.out.print(m + " ");
m++;
}
System.out.println();
}
}
// Driver Code
public static void main (String[] args)
{
int n = 3;
printPattern(n);
}
}
// This code is contributed
// by anuj_67.
C#
1553
Chapter 225. Print concentric rectangular pattern in a 2d matrix
1554
Chapter 225. Print concentric rectangular pattern in a 2d matrix
Output
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
Improved By : vt_m
Source
https://www.geeksforgeeks.org/print-concentric-rectangular-pattern-in-a-2d-matrix/
1555
Chapter 226
Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
The idea is simple, we traverse matrix in spiral form and put all traversed elements in a
1556
Chapter 226. Print matrix in antispiral form
stack. Finally one by one elements from stack and print them.
C++
1557
Chapter 226. Print matrix in antispiral form
}
while (!stk.empty())
{
cout << stk.top() << " ";
stk.pop();
}
}
/* Driver program to test above functions */
int main()
{
int mat[R][C] =
{
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
antiSpiralTraversal(R-1, C-1, mat);
return 0;
}
Java
1558
Chapter 226. Print matrix in antispiral form
1559
Chapter 226. Print matrix in antispiral form
mat);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python 3
1560
Chapter 226. Print matrix in antispiral form
stk.append(a[i][l])
l += 1
while len(stk) != 0:
print(str(stk[-1]), end = " ")
stk.pop()
# Driver Code
mat = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]];
antiSpiralTraversal(R - 1, C - 1, mat)
# This code is contributed
# by ChitraNayal
Output:
12 13 14 9 8 7 6 11 16 17 18 19 20 15 10 5 4 3 2 1
Improved By : ChitraNayal
Source
https://www.geeksforgeeks.org/print-matrix-antispiral-form/
1561
Chapter 227
1562
Chapter 227. Print matrix in diagonal pattern
2. If isUp = 1 then start printing elements by incrementing column index and decrement-
ing the row index.
3. Similarly if isUp = 0, then decrement the column index and increment the row index.
4.
C++
1563
Chapter 227. Print matrix in diagonal pattern
Java
1564
Chapter 227. Print matrix in diagonal pattern
1565
Chapter 227. Print matrix in diagonal pattern
{
j = j + 2 ; i--;
}
}
// Revert the isUp to change the direction
isUp = !isUp;
}
}
//Driver code
public static void main (String[] args)
{
int mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
printMatrixDiagonal(mat, n);
}
}
//This code is contributed by Anant Agarwal.
Python 3
1566
Chapter 227. Print matrix in diagonal pattern
C#
1567
Chapter 227. Print matrix in diagonal pattern
1568
Chapter 227. Print matrix in diagonal pattern
// Driver code
public static void Main ()
{
int [,]mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
printMatrixDiagonal(mat, n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// php program to print matrix
// in diagonal order
$MAX = 100;
function printMatrixDiagonal($mat, $n)
{
// Initialize indexes of element
// to be printed next
$i = 0;
$j = 0 ;
// Direction is initially
// from down to up
$isUp = true;
// Traverse the matrix till
// all elements get traversed
for ($k = 0;$k < $n * $n�
{
// If isUp = true then traverse
// from downward to upward
if ($isUp)
{
for ( ;$i >= 0 && $j < $n;$j++, $i--)
{
echo $mat[$i][$j]." ";
$k++;
}
// Set i and j according
1569
Chapter 227. Print matrix in diagonal pattern
// to direction
if ($i < 0 && $j <= $n - 1)
$i = 0;
if ($j == $n)
{
$i = $i + 2;
$j--;
}
}
// If isUp = 0 then
// traverse up to down
else
{
for ( ; $j >= 0 &&
$i<$n ; $i++ , $j--)
{
echo $mat[$i][$j]." ";
$k++;
}
// Set i and j according
// to direction
if ($j < 0 && $i <= $n - 1)
$j = 0;
if ($i == $n)
{
$j = $j + 2;
$i--;
}
}
// Revert the isUp to
// change the direction
$isUp = !$isUp;
}
}
// Driver code
$mat= array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
$n = 3;
printMatrixDiagonal($mat, $n);
// This code is contributed by mits
?>
1570
Chapter 227. Print matrix in diagonal pattern
Output:
1 2 4 7 5 3 6 8 9
Source
https://www.geeksforgeeks.org/print-matrix-diagonal-pattern/
1571
Chapter 228
Output : 10 20 30 40 45 35 25 15 27 29
37 48 50 39 33 32
1572
Chapter 228. Print matrix in snake pattern
We traverse all rows. For every row, we check if it is even or odd. If even, we print from
left to right else print from right to left.
C++
1573
Chapter 228. Print matrix in snake pattern
if (i % 2 == 0) {
for (int j = 0; j < N; j++)
cout << mat[i][j] << " ";
// If current row is odd, print from
// right to left
} else {
for (int j = N - 1; j >= 0; j--)
cout << mat[i][j] << " ";
}
}
}
// Driver code
int main()
{
int mat[][] = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
print(mat);
return 0;
}
Java
1574
Chapter 228. Print matrix in snake pattern
else
{
for (int j = mat[0].length - 1; j >= 0; j--)
System.out.print(mat[i][j] +" ");
}
}
}
// Driver code
public static void main(String[] args)
{
int mat[][] = new int[][]
{
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 }
};
print(mat);
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python 3
1575
Chapter 228. Print matrix in snake pattern
else:
for j in range(N - 1, -1, -1):
print(str(mat[i][j]),
end = " ")
# Driver code
mat = [[ 10, 20, 30, 40 ],
[ 15, 25, 35, 45 ],
[ 27, 29, 37, 48 ],
[ 32, 33, 39, 50 ]]
printf(mat)
# This code is contributed
# by ChitraNayal
C#
// C# program to print
// matrix in snake order
using System;
class GFG
{
static void print(int [,]mat)
{
// Traverse through all rows
for (int i = 0;
i < mat.GetLength(0); i++)
{
// If current row is
// even, print from
// left to right
if (i % 2 == 0)
{
for (int j = 0;
j < mat.GetLength(1); j++)
Console.Write(mat[i, j] + " ");
// If current row is
// odd, print from
// right to left
}
else
{
for (int j = mat.GetLength(1) - 1;
j >= 0; j--)
1576
Chapter 228. Print matrix in snake pattern
PHP
<?php
// PHP program to print
// matrix in snake order
$M= 4;
$N =4;
function printLN($mat)
{
global $M;
global $N;
// Traverse through all rows
for ($i = 0; $i < $M; $i++)
{
// If current row is even,
// print from left to right
if ($i % 2 == 0)
{
for ($j = 0; $j < $N; $j++)
echo $mat[$i][$j], " ";
// If current row is odd,
// print from right to left
}
else
1577
Chapter 228. Print matrix in snake pattern
{
for ($j = $N - 1; $j >= 0; $j--)
echo $mat[$i][$j] , " ";
}
}
}
// Driver code
$mat = array(array(10, 20, 30, 40),
array(15, 25, 35, 45),
array(27, 29, 37, 48),
array(32, 33, 39, 50));
printLN($mat);
// This code is contributed by ajit
?>
Output :
10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32
Source
https://www.geeksforgeeks.org/print-matrix-snake-pattern/
1578
Chapter 229
Example:
Input:
1 2 3
1579
Chapter 229. Print matrix in zag-zag fashion
4 5 6
7 8 9
Output:
1 2 4 7 5 3 6 8 9
1580
Chapter 229. Print matrix in zag-zag fashion
}
if (len == mn)
break;
// Update row or col vlaue according
// to the last increment
if (row_inc)
++row, row_inc = false;
else
++col, row_inc = true;
}
// Update the indexes of row and col variable
if (row == 0) {
if (col == m - 1)
++row;
else
++col;
row_inc = 1;
}
else {
if (row == n - 1)
++col;
else
++row;
row_inc = 0;
}
// Print the next half zig-zag pattern
int MAX = max(m, n) - 1;
for (int len, diag = MAX; diag > 0; --diag) {
if (diag > mn)
len = mn;
else
len = diag;
for (int i = 0; i < len; ++i) {
cout << arr[row][col] << " ";
if (i + 1 == len)
break;
// Update row or col vlaue according
// to the last increment
if (row_inc)
++row, --col;
1581
Chapter 229. Print matrix in zag-zag fashion
else
++col, --row;
}
// Update the indexes of row and col variable
if (row == 0 || col == m - 1) {
if (col == m - 1)
++row;
else
++col;
row_inc = true;
}
else if (col == 0 || row == n - 1) {
if (row == n - 1)
++col;
else
++row;
row_inc = false;
}
}
}
// Driver code
int main()
{
int matrix[][3] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
zigZagMatrix(matrix, 3, 3);
return 0;
}
Java
1582
Chapter 229. Print matrix in zag-zag fashion
1583
Chapter 229. Print matrix in zag-zag fashion
++col;
else
++row;
row_inc = false;
}
// Print the next half zig-zag pattern
int MAX = Math.max(m, n) - 1;
for (int len, diag = MAX; diag > 0; --diag) {
if (diag > mn)
len = mn;
else
len = diag;
for (int i = 0; i < len; ++i) {
System.out.print(arr[row][col] + " ");
if (i + 1 == len)
break;
// Update row or col vlaue according
// to the last increment
if (row_inc) {
++row;
--col;
} else {
++col;
--row;
}
}
// Update the indexes of row and col variable
if (row == 0 || col == m - 1) {
if (col == m - 1)
++row;
else
++col;
row_inc = true;
}
else if (col == 0 || row == n - 1) {
if (row == n - 1)
++col;
else
++row;
1584
Chapter 229. Print matrix in zag-zag fashion
row_inc = false;
}
}
}
// Driver code
public static void main(String[] args) {
int matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
zigZagMatrix(matrix, 3, 3);
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
1585
Chapter 229. Print matrix in zag-zag fashion
1586
Chapter 229. Print matrix in zag-zag fashion
1587
Chapter 229. Print matrix in zag-zag fashion
if (row_inc) {
++row;
--col;
}
else {
++col;
--row;
}
}
// Update the indexes of
// row and col variable
if (row == 0 || col == m - 1) {
if (col == m - 1)
++row;
else
++col;
row_inc = true;
}
else if (col == 0 || row == n - 1) {
if (row == n - 1)
++col;
else
++row;
row_inc = false;
}
}
}
// Driver code
public static void Main()
{
int[, ] matrix = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
zigZagMatrix(matrix, 3, 3);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to print
1588
Chapter 229. Print matrix in zag-zag fashion
1589
Chapter 229. Print matrix in zag-zag fashion
break;
// Update row or col
// vlaue according
// to the last increment
if ($row_inc)
{
++$row; $row_inc = false;
}
else
{
++$col; $row_inc = true;
}
}
// Update the indexes of
// row and col variable
if ($row == 0)
{
if ($col == $m - 1)
++$row;
else
++$col;
$row_inc = 1;
}
else
{
if ($row == $n - 1)
++$col;
else
++$row;
$row_inc = 0;
}
// Print the next half
// zig-zag pattern
$MAX = max($m, $n) - 1;
for ($len, $diag = $MAX;
$diag > 0; --$diag)
{
if ($diag > $mn)
$len = $mn;
else
$len = $diag;
for ($i = 0;
$i < $len; ++$i)
{
1590
Chapter 229. Print matrix in zag-zag fashion
1591
Chapter 229. Print matrix in zag-zag fashion
zigZagMatrix($matrix, 3, 3);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
1 2 4 7 5 3 6 8 9
Source
https://www.geeksforgeeks.org/print-matrix-zag-zag-fashion/
1592
Chapter 230
We strongly recommend you to minimize your browser and try this yourself
first.
A Simple Solution is to consider all possible sub-squares of size k x k in our input matrix
and find the one which has maximum sum. Time complexity of above solution is O(N2 k2 ).
We can solve this problem in O(N2 ) time. This problem is mainly an extension of this
problem of printing all sums. The idea is to preprocess the given square matrix. In the
1593
Chapter 230. Print maximum sum square sub-matrix of given size
preprocessing step, calculate sum of all vertical strips of size k x 1 in a temporary square
matrix stripSum[][]. Once we have sum of all vertical strips, we can calculate sum of first
sub-square in a row as sum of first k strips in that row, and for remaining sub-squares, we
can calculate sum in O(1) time by removing the leftmost strip of previous subsquare and
adding the rightmost strip of new square.
Below is C++ implementation of above idea.
1594
Chapter 230. Print maximum sum square sub-matrix of given size
// 2: CALCULATE SUM of Sub-Squares using stripSum[][]
for (int i=0; i<N-k+1; i++)
{
// Calculate and print sum of first subsquare
// in this row
int sum = 0;
for (int j = 0; j<k; j++)
sum += stripSum[i][j];
// Update max_sum and position of result
if (sum > max_sum)
{
max_sum = sum;
pos = &(mat[i][0]);
}
// Calculate sum of remaining squares in
// current row by removing the leftmost
// strip of previous sub-square and adding
// a new strip
for (int j=1; j<N-k+1; j++)
{
sum += (stripSum[i][j+k-1] - stripSum[i][j-1]);
// Update max_sum and position of result
if (sum > max_sum)
{
max_sum = sum;
pos = &(mat[i][j]);
}
}
}
// Print the result matrix
for (int i=0; i<k; i++)
{
for (int j=0; j<k; j++)
cout << *(pos + i*N + j) << " ";
cout << endl;
}
}
// Driver program to test above function
int main()
{
int mat[N][N] = {{1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
1595
Chapter 230. Print maximum sum square sub-matrix of given size
{3, 8, 6, 7, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5},
};
int k = 3;
cout << "Maximum sum 3 x 3 matrix is\n";
printMaxSumSub(mat, k);
return 0;
}
Output:
Related Articles:
Given an n x n square matrix, find sum of all sub-squares of size k x k
Maximum sum rectangle in a 2D matrix
Source
https://www.geeksforgeeks.org/print-maximum-sum-square-sub-matrix-of-given-size/
1596
Chapter 231
Input: n = 5
Output:
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
We strongly recommend you to minimize your browser and try this yourself
first.
The solution becomes simple if extra space is allowed. We allocate memory for n x n matrix
and for every element starting from n*n to 1, we start filling out matrix in spiral order. To
maintain the spiral order four loops are used, each for top, right, bottom and left corner of
the matrix.
But how to solve it in O(1) space?
An n x n matrix has ceil(n/2) square cycles. A cycle is formed by ith row, (n-i+1)th column,
(n-i+1)th row and ith column where i varies from 1 to ceil(n/2).
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
1597
Chapter 231. Print n x n spiral matrix using O(1) extra space
1. The first cycle is formed by elements of its first row, last column, last row and first
column (marked by red). The first cycle consists of elements from n*n to (n-2)*(n-2)
+ 1. i.e. from 25 to 10.
2. The second cycle is formed by elements of second row, second-last column, second-last
row and second column(marked by blue). The second cycle consists of elements from
(n-2)*(n-2) to (n-4)*(n-4) + 1. i.e. from 9 to 2.
3. The third cycle is formed by elements of third row, third-last column, third-last row
and third column(marked by black). The third cycle consists of elements from (n-
4)*(n-4) to 1. i.e. only 1.
The idea is for each square cycle, we associate a marker to it. For outer cycle, the marker
will have value 0, for second cycle, it will have value 1 and for third cycle it has value 2. In
general for a n x n matrix, i’th cycle will have marker value of i – 1.
If we divide the matrix into two parts, upper right triangle(marked by orange) and lower
left triangle(marked by green), then using the marker x, we can easily calculate the value
that will be present at the index(i, j) in any n x n spiral matrix using the below formula –
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
C++
1598
Chapter 231. Print n x n spiral matrix using O(1) extra space
Java
1599
Chapter 231. Print n x n spiral matrix using O(1) extra space
// x stores the layer in which (i, j)th
// element lies
int x;
// Finds minimum of four inputs
x = Math.min(Math.min(i, j),
Math.min(n - 1 - i, n - 1 - j));
// For upper right half
if (i <= j)
System.out.print((n - 2 * x) * (n - 2 * x) -
(i - x) - (j - x) + "\t");
// for lower left half
else
System.out.print((n - 2 * x - 2) * (n - 2 * x - 2) +
(i - x) + (j - x) + "\t");
}
System.out.println();
}
}
// Driver code
public static void main(String args[])
{
int n = 5;
// print a n x n spiral matrix in O(1) space
printSpiral(n);
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
1600
Chapter 231. Print n x n spiral matrix using O(1) extra space
C#
// C# program to print a n x n
// spiral matrix in clockwise
// direction using O(1) space
using System;
class GFG {
// Prints spiral matrix of
// size n x n containing
// numbers from 1 to n x n
static void printSpiral(int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// x stores the layer in which
// (i, j)th element lies
int x;
// Finds minimum of four inputs
x = Math.Min(Math.Min(i, j),
1601
Chapter 231. Print n x n spiral matrix using O(1) extra space
Math.Min(n - 1 - i, n - 1 - j));
// For upper right half
if (i <= j)
Console.Write((n - 2 * x) *
(n - 2 * x) -
(i - x) - (j - x) + "\t");
// for lower left half
else
Console.Write((n - 2 * x - 2) *
(n - 2 * x - 2) +
(i - x) + (j - x) + "\t");
}
Console.WriteLine();
}
}
// Driver code
public static void Main()
{
int n = 5;
// print a n x n spiral
// matrix in O(1) space
printSpiral(n);
}
}
// This code is contributed by KRV
PHP
<?php
// PHP program to print a n x n
// spiral matrix in clockwise
// direction using O(1) space
// Prints spiral matrix of size
// n x n containing numbers
// from 1 to n x n
function printSpiral($n)
{
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// x stores the layer in
1602
Chapter 231. Print n x n spiral matrix using O(1) extra space
Output :
25 24 23 22 21
10 9 8 7 20
11 2 1 6 19
12 3 4 5 18
13 14 15 16 17
Exercise
For a given number n, print a n x n spiral matrix in counter clockwise direction using O(1)
space.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : KRV, jit_t
1603
Chapter 231. Print n x n spiral matrix using O(1) extra space
Source
https://www.geeksforgeeks.org/print-n-x-n-spiral-matrix-using-o1-extra-space/
1604
Chapter 232
A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
Z
For example,
Input: “GEEK”
Output:
Move Down
Move Right
Press OK
Move Up
Move Right
Move Right
Move Right
1605
Chapter 232. Print shortest path to print a string on screen
Press OK
Press OK
Move Left
Move Left
Move Left
Move Left
Move Down
Move Down
Press OK
The idea is to consider screen as 2D-matrix of characters. Then we consider all characters
of given string one by one and print out the shortest path between current character and
next character in the matrix. In order to find shortest path, we consider the coordinates of
current character and next character in the matrix. Based on the difference between x and
y values of current and next character’s coordinates, we move left, right, top or bottom. i.e.
1606
Chapter 232. Print shortest path to print a string on screen
curX--;
}
// Move Left if destination is to the left
while (curY > nextY)
{
cout << "Move Left" << endl;
curY--;
}
// Move down if destination is below
while (curX < nextX)
{
cout << "Move Down" << endl;
curX++;
}
// Move Right if destination is to the right
while (curY < nextY)
{
cout << "Move Right" << endl;
curY++;
}
// At this point, destination is reached
cout << "Press OK" << endl;
i++;
}
}
// Driver code
int main()
{
string str = "COZY";
printPath(str);
return 0;
}
Java
1607
Chapter 232. Print shortest path to print a string on screen
1608
Chapter 232. Print shortest path to print a string on screen
{
String str = "COZY";
printPath(str);
}
}
// Contributed by Pramod Kumar
C#
1609
Chapter 232. Print shortest path to print a string on screen
{
Console.WriteLine("Move Left");
curY--;
}
// Move down if destination
// is below
while (curX < nextX)
{
Console.WriteLine("Move Down");
curX++;
}
// Move Right if destination
// is to the right
while (curY < nextY)
{
Console.WriteLine("Move Right");
curY++;
}
// At this point, destination
// is reached
Console.WriteLine("Press OK");
i++;
}
}
// Driver Code
public static void Main ()
{
String str = "COZY";
printPath(str);
}
}
// This Code is contributed by nitin mittal.
Output:
Move Right
Move Right
Press OK
Move Down
Move Down
Move Right
Move Right
1610
Chapter 232. Print shortest path to print a string on screen
Press OK
Move Left
Move Left
Move Left
Move Left
Move Down
Move Down
Move Down
Press OK
Move Up
Move Right
Move Right
Move Right
Move Right
Press OK
Source
https://www.geeksforgeeks.org/print-shortest-path-print-string-screen/
1611
Chapter 233
Print the corner elements and their sum in a 2-D matrix - GeeksforGeeks
Given a 2-D matrix. The task is to print its corner elements and the sum of the corner
elements.
Examples: That
Input: 2 7 5 5 5 8 2
2 4 4 8 8 3 5
6 9 3 4 5 4 3
7 1 3 7 4 2 8
6 9 6 5 6 8 9
8 6 9 9 8 3 6
Output: Corner elements: 2 8 2 6, Corner_Sum = 18
Input: 6 4 6 9
2 6 1 8
5 5 2 2
4 4 1 3
Output: Corner elements: 6 4 9 3, Corner_Sum = 22
1612
Chapter 233. Print the corner elements and their sum in a 2-D matrix
Java
1613
Chapter 233. Print the corner elements and their sum in a 2-D matrix
class GFG
{
static final int n = 3;
static final int m = 3;
// function to print corner
// elements their sum
static void printCornerElements(int arr[][])
{
// print the corner elements
System.out.println("left top corner: " +
arr[0][0]);
System.out.println("right top corner: " +
arr[0][m - 1]);
System.out.println("left bottom corner: " +
arr[n - 1][0]);
System.out.println("right bottom corner: " +
arr[n - 1][m - 1]);
// print the sum of corner elements
System.out.print("\nCorner elements Sum = ");
System.out.println(arr[0][0] + arr[0][m - 1] +
arr[n - 1][0] +
arr[n - 1][m - 1]);
}
// Driver Code
public static void main(String args[])
{
int arr[][] ={{1, 2, 4},
{5, 6, 8},
{8, 3, 1}};
// Function to print the corner
// elements and their sum
printCornerElements(arr);
}
}
// This code is contributed
// by Ankita_Saini
Python3
1614
Chapter 233. Print the corner elements and their sum in a 2-D matrix
C#
// C# program to print
// the corner elements
// and their sum
using System;
class GFG
{
static int n = 3;
static int m = 3;
// function to print corner
1615
Chapter 233. Print the corner elements and their sum in a 2-D matrix
PHP
<?php
// PHP program to print the corner
// elements and their sum
$n = 3;
$m = 3;
// function to print corner
// elements their sum
function printCornerElements(&$arr)
1616
Chapter 233. Print the corner elements and their sum in a 2-D matrix
{
global $n, $m;
// print the corner elements
echo "left top corner: " .
$arr[0][0];
echo "\nright top corner: " .
$arr[0][$m - 1];
echo "\nleft bottom corner: " .
$arr[$n - 1][0];
echo "\nright bottom corner: " .
$arr[$n - 1][$m - 1];
// print the sum of corner elements
echo "\n\nCorner elements Sum = ".
($arr[0][0] + $arr[0][$m - 1] +
$arr[$n - 1][0] +
$arr[$n - 1][$m - 1]);
}
// Driver Code
$arr = array(array( 1, 2, 4 ),
array( 5, 6, 8 ),
array( 8, 3, 1 ));
// Function to print the corner
// elements and their sum
printCornerElements($arr);
// This code is contributed
// by ChitraNayal
?>
Output:
Source
https://www.geeksforgeeks.org/print-the-corner-elements-and-their-sum-in-a-2-d-matrix/
1617
Chapter 234
Input:
{0, 1, 0, 0, 1}
{1, 0, 1, 1, 0}
{0, 1, 0, 0, 1}
{1, 1, 1, 0, 0}
Output:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0
Method 1 (Simple)
A simple approach is to check each row with all processed rows. Print the first row. Now,
starting from the second row, for each row, compare the row with already processed rows.
If the row matches with any of the processed rows, don’t print it. If the current row doesn’t
match with any row, print it.
Time complexity: O( ROW^2 x COL )
Auxiliary Space: O( 1 )
Method 2 (Use Binary Search Tree)
Find the decimal equivalent of each row and insert it into BST. Each node of the BST will
contain two fields, one field for the decimal value, other for row number. Do not insert a
node if it is duplicated. Finally, traverse the BST and print the corresponding rows.
Time complexity: O( ROW x COL + ROW x log( ROW ) )
Auxiliary Space: O( ROW )
1618
Chapter 234. Print unique rows in a given boolean matrix
//Given a binary matrix of M X N of integers, you need to return only unique rows of binary arra
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ROW 4
#define COL 5
// A Trie node
typedef struct Node
{
bool isEndOfCol;
struct Node *child[2]; // Only two children needed for 0 and 1
} Node;
// A utility function to allocate memory for a new Trie node
Node* newNode()
{
Node* temp = (Node *)malloc( sizeof( Node ) );
temp->isEndOfCol = 0;
temp->child[0] = temp->child[1] = NULL;
return temp;
}
// Inserts a new matrix row to Trie. If row is already
// present, then returns 0, otherwise insets the row and
// return 1
bool insert( Node** root, int (*M)[COL], int row, int col )
{
// base case
if ( *root == NULL )
*root = newNode();
// Recur if there are more entries in this row
if ( col < COL )
return insert ( &( (*root)->child[ M[row][col] ] ), M, row, col+1 );
else // If all entries of this row are processed
1619
Chapter 234. Print unique rows in a given boolean matrix
{
// unique row found, return 1
if ( !( (*root)->isEndOfCol ) )
return (*root)->isEndOfCol = 1;
// duplicate row found, return 0
return 0;
}
}
// A utility function to print a row
void printRow( int (*M)[COL], int row )
{
int i;
for( i = 0; i < COL; ++i )
printf( "%d ", M[row][i] );
printf("\n");
}
// The main function that prints all unique rows in a
// given matrix.
void findUniqueRows( int (*M)[COL] )
{
Node* root = NULL; // create an empty Trie
int i;
// Iterate through all rows
for ( i = 0; i < ROW; ++i )
// insert row to TRIE
if ( insert(&root, M, i, 0) )
// unique row found, print it
printRow( M, i );
}
// Driver program to test above functions
int main()
{
int M[ROW][COL] = {{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 0, 0}
};
findUniqueRows( M );
return 0;
}
1620
Chapter 234. Print unique rows in a given boolean matrix
1621
Chapter 234. Print unique rows in a given boolean matrix
Source
https://www.geeksforgeeks.org/print-unique-rows/
1622
Chapter 235
1623
Chapter 235. Printing all solutions in N-Queen Problem
In previous post, we have discussed an approach that prints only one possible solution, so
now in this post the task is to print all solutions in N-Queen Problem. The solution discussed
here is an extension of same approach.
Backtracking Algorithm
The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this
row and column as part of the solution. If we do not find such a row due to clashes then we
backtrack and return false.
There is only a slight modification in above algorithm that is highlighted in the code.
1624
Chapter 235. Printing all solutions in N-Queen Problem
backtracking */
#include<bits/stdc++.h>
#define N 4
/* A utility function to print solution */
void printSolution(int board[N][N])
{
static int k = 1;
printf("%d-\n",k++);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
printf("\n");
}
/* A utility function to check if a queen can
be placed on board[row][col]. Note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
So we need to check only left side for
attacking queens */
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i])
return false;
/* Check upper diagonal on left side */
for (i=row, j=col; i>=0 && j>=0; i--, j--)
if (board[i][j])
return false;
/* Check lower diagonal on left side */
for (i=row, j=col; j>=0 && i<N; i++, j--)
if (board[i][j])
return false;
return true;
}
/* A recursive utility function to solve N
Queen problem */
1625
Chapter 235. Printing all solutions in N-Queen Problem
1626
Chapter 235. Printing all solutions in N-Queen Problem
int board[N][N];
memset(board, 0, sizeof(board));
if (solveNQUtil(board, 0) == false)
{
printf("Solution does not exist");
return ;
}
return ;
}
// driver program to test above function
int main()
{
solveNQ();
return 0;
}
Output:
1-
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
2-
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
Source
https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/
1627
Chapter 236
However, the order in which we parenthesize the product affects the number of simple arith-
metic operations needed to compute the product, or the efficiency. For example, suppose A
is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,
1628
Chapter 236. Printing brackets in Matrix Chain Multiplication Problem
This problem is mainly an extension of previous post. In the previous post, we have discussed
algorithm for finding optimal cost only. Here we need print parenthssization also.
The idea is to store optimal break point for every subexpression (i, j) in a 2D array
bracket[n][n]. Once we have bracket array us constructed, we can print parenthesization
using below code.
print "(";
1629
Chapter 236. Printing brackets in Matrix Chain Multiplication Problem
print ")";
}
// C++ program to print optimal parenthesization
// in matrix chain multiplication.
#include<bits/stdc++.h>
using namespace std;
// Function for printing the optimal
// parenthesization of a matrix chain product
void printParenthesis(int i, int j, int n,
int *bracket, char &name)
{
// If only one matrix left in current segment
if (i == j)
{
cout << name++;
return;
}
cout << "(";
// Recursively put brackets around subexpression
// from i to bracket[i][j].
// Note that "*((bracket+i*n)+j)" is similar to
// bracket[i][j]
printParenthesis(i, *((bracket+i*n)+j), n,
bracket, name);
// Recursively put brackets around subexpression
// from bracket[i][j] + 1 to j.
printParenthesis(*((bracket+i*n)+j) + 1, j,
n, bracket, name);
cout << ")";
}
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
// Please refer below article for details of this
// function
// https://goo.gl/k6EYKj
void matrixChainOrder(int p[], int n)
{
/* For simplicity of the program, one extra
row and one extra column are allocated in
m[][]. 0th row and 0th column of m[][]
1630
Chapter 236. Printing brackets in Matrix Chain Multiplication Problem
1631
Chapter 236. Printing brackets in Matrix Chain Multiplication Problem
// Driver code
int main()
{
int arr[] = {40, 20, 30, 10, 30};
int n = sizeof(arr)/sizeof(arr[0]);
matrixChainOrder(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/
1632
Chapter 237
Input: TOP
Output:
X T X
T O P
X P X
Input: FEVER
Output:
X X F X X
X X E X X
F E V E R
X X E X X
X X R X X
Approach:
The idea is simple. First we can access every element of the matrix and make it ‘X’. Then
we will insert the characters of the string in the middle row as well as in the middle column
of the matrix. For example, we have string of length 5. So we will need a (5X5) matrix for
it.
1633
Chapter 237. Printing string in plus ‘+’ pattern in the matrix
To access the middle column of the matrix, column index is made constant and is equal to
(n/2), where n is the length of the string. Row index will go from 0 to (n-1) for it.
To access the middle row, the row index will be made constant and equal to (n/2) and the
column index will go from 0 to (n-1).
Below is the implementation of above approach:
CPP
1634
Chapter 237. Printing string in plus ‘+’ pattern in the matrix
arr[i][j] = 'X';
}
}
/* Now, we will place the characters
of the string in the matrix, such
that a cross is formed in it.*/
for (int i = 0; i < n; i++)
{
/* here the characters of the
string will be added in the
middle column of our array.*/
arr[i][m] = str[i];
}
for (int i = 0; i < n; i++)
{
// here the characters of the
// string will be added in the
// middle row of our array.
arr[m][i] = str[i];
}
/* Now finally, we will print
the array*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << arr[i][j] << " ";
}
cout << "\n";
}
}
}
// driver code
int main()
{
string str = "PICTURE";
carveCross(str);
return 0;
}
Java
1635
Chapter 237. Printing string in plus ‘+’ pattern in the matrix
// Function to make a cross in the matrix
static void carveCross(String str) {
int n = str.length();
if (n % 2 == 0) {
// As, it is not possible to make
// the cross exactly in the middle of
// the matrix with an even length string.
System.out.print("Not possible. Please enter "
+ "odd length string.\n");
}
else {
// declaring a 2D array i.e a matrix
char arr[][] = new char[max][max];
int m = n / 2;
// Now, we will fill all the
// elements of the array with 'X'
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
arr[i][j] = 'X';
}
}
// Now, we will place the characters
// of the string in the matrix, such
// that a cross is formed in it.
for (int i = 0; i < n; i++) {
// here the characters of the
// string will be added in the
// middle column of our array.
arr[i][m] = str.charAt(i);
}
for (int i = 0; i < n; i++) {
// here the characters of the
// string will be added in the
// middle row of our array.
arr[m][i] = str.charAt(i);
}
// Now finally, we will print
1636
Chapter 237. Printing string in plus ‘+’ pattern in the matrix
C#
1637
Chapter 237. Printing string in plus ‘+’ pattern in the matrix
{
for (int j = 0; j < n; j++)
{
arr[i,j] = 'X';
}
}
// Now, we will place the characters
// of the string in the matrix, such
// that a cross is formed in it.
for (int i = 0; i < n; i++) {
// here the characters of the
// string will be added in the
// middle column of our array.
arr[i,m] = str[i];
}
for (int i = 0; i < n; i++) {
// here the characters of the
// string will be added in the
// middle row of our array.
arr[m,i] = str[i];
}
// Now finally, we will print
// the array
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(arr[i,j] + " ");
}
Console.WriteLine();
}
}
}
// Driver code
public static void Main() {
string str = "PICTURE";
carveCross(str);
}
}
// This code is contributed by vt_m.
Output:
1638
Chapter 237. Printing string in plus ‘+’ pattern in the matrix
X X X P X X X
X X X I X X X
X X X C X X X
P I C T U R E
X X X U X X X
X X X R X X X
X X X E X X X
Source
https://www.geeksforgeeks.org/printing-string-plus-pattern-matrix/
1639
Chapter 238
1. Any live cell with fewer than two live neighbors dies, as if caused by under population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by overpopulation.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduc-
tion.
Examples:
The ‘*’ represent an alive cell and the ‘.’ represent a dead cell.
Input : ..........
...**.....
....*.....
..........
..........
Output: ..........
...**.....
...**.....
..........
..........
..........
Input : ..........
...**.....
1640
Chapter 238. Program for Conway’s Game Of Life
....*.....
..........
..........
...**.....
..**......
.....*....
....*.....
..........
Output: ..........
...**.....
...**.....
..........
..........
..***.....
..**......
...**.....
..........
..........
Here is a simple Java implementation of the Game Of Life. Grid in initialized with 0’s
representing the dead cells and 1’s representing alive cells. The generate() function loops
through every cell and counts it’s neighbors. Based on that values, the aforementioned
rules are implemented. The following implementation ignores the edge cells as it supposed
to be played on an infinite plane.
Java
1641
Chapter 238. Program for Conway’s Game Of Life
1642
Chapter 238. Program for Conway’s Game Of Life
C#
1643
Chapter 238. Program for Conway’s Game Of Life
};
// Displaying the grid
Console.WriteLine("Original Generation");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
if (grid[i,j] == 0)
Console.Write(".");
else
Console.Write("*");
}
Console.WriteLine();
}
Console.WriteLine();
nextGeneration(grid, M, N);
}
// Function to print next generation
static void nextGeneration(int [,]grid,
int M, int N)
{
int[,] future = new int[M,N];
// Loop through every cell
for (int l = 1; l < M - 1; l++)
{
for (int m = 1; m < N - 1; m++)
{
// finding no Of Neighbours
// that are alive
int aliveNeighbours = 0;
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++)
aliveNeighbours +=
grid[l + i,m + j];
// The cell needs to be subtracted
// from its neighbours as it was
// counted before
aliveNeighbours -= grid[l,m];
// Implementing the Rules of Life
// Cell is lonely and dies
if ((grid[l,m] == 1) &&
1644
Chapter 238. Program for Conway’s Game Of Life
Output:
Original Generation
..........
...**.....
....*.....
..........
..........
...**.....
..**......
.....*....
1645
Chapter 238. Program for Conway’s Game Of Life
....*.....
..........
Next Generation
..........
...**.....
...**.....
..........
..........
..***.....
..**......
...**.....
..........
..........
The above implementation is very basic. Try coming up with a more efficient implementation
and be sure to comment it below. Also for fun try creating your own rule for cellular
Automata.
Conways’s Game Of Life is a Cellular Automation Method created by John Conway. This
game was created with Biology in mind but has been applied in various fields such as
Graphics, terrain generation,etc..
Improved By : Sam007
Source
https://www.geeksforgeeks.org/program-for-conways-game-of-life/
1646
Chapter 239
1647
Chapter 239. Program for Gauss-Jordan Elimination Method
1648
Chapter 239. Program for Gauss-Jordan Elimination Method
Examples :
Input : 2y + z = 4
x + y + 2z = 6
2x + y + z = 7
Output :
Final Augumented Matrix is :
1 0 0 2.2
0 2 0 2.8
0 0 -2.5 -3
1649
Chapter 239. Program for Gauss-Jordan Elimination Method
Performing R1
1650
Chapter 239. Program for Gauss-Jordan Elimination Method
1651
Chapter 239. Program for Gauss-Jordan Elimination Method
}
}
}
return flag;
}
// Function to print the desired result
// if unique solutions exists, otherwise
// prints no solution or infinite solutions
// depending upon the input given.
void PrintResult(float a[][M], int n, int flag)
{
cout << "Result is : ";
if (flag == 2)
cout << "Infinite Solutions Exists" << endl;
else if (flag == 3)
cout << "No Solution Exists" << endl;
// Printing the solution by dividing constants by
// their respective diagonal elements
else {
for (int i = 0; i < n; i++)
cout << a[i][n] / a[i][i] << " ";
}
}
// To check whether infinite solutions
// exists or no solution exists
int CheckConsistency(float a[][M], int n, int flag)
{
int i, j;
float sum;
// flag == 2 for infinite solution
// flag == 3 for No solution
flag = 3;
for (i = 0; i < n; i++)
{
sum = 0;
for (j = 0; j < n; j++)
sum = sum + a[i][j];
if (sum == a[i][j])
flag = 2;
}
return flag;
}
1652
Chapter 239. Program for Gauss-Jordan Elimination Method
// Driver code
int main()
{
float a[M][M] = {{ 0, 2, 1, 4 },
{ 1, 1, 2, 6 },
{ 2, 1, 1, 7 }};
// Order of Matrix(n)
int n = 3, flag = 0;
// Performing Matrix transformation
flag = PerformOperation(a, n);
if (flag == 1)
flag = CheckConsistency(a, n, flag);
// Printing Final Matrix
cout << "Final Augumented Matrix is : " << endl;
PrintMatrix(a, n);
cout << endl;
// Printing Solutions(if exist)
PrintResult(a, n, flag);
return 0;
}
Output:
Applications :
1653
Chapter 239. Program for Gauss-Jordan Elimination Method
Source
https://www.geeksforgeeks.org/program-for-gauss-jordan-elimination-method/
1654
Chapter 240
In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n
x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted
by “ I “. Sometimes U or E is also used to denote an Identity Matrix.
A property of the identity matrix is that it leaves a matrix unchanged if it is
multiplied by an Identity Matrix.
Examples:
Input : 2
Output : 1 0
0 1
Input : 4
Output : 1 0 0 0
0 1 0 0
0 0 1 0
1655
Chapter 240. Program for Identity Matrix
0 0 0 1
The explanation is simple. We need to make all
the elements of principal or main diagonal as
1 and everything else as 0.
C/C++
Java
1656
Chapter 240. Program for Identity Matrix
{
int row, col;
for (row = 0; row < num; row++)
{
for (col = 0; col < num; col++)
{
// Checking if row is equal to column
if (row == col)
System.out.print( 1+" ");
else
System.out.print( 0+" ");
}
System.out.println();
}
return 0;
}
// Driver Code
public static void main(String args[])
{
int size = 5;
identity(size);
}
}
/*This code is contributed by Nikita tiwari.*/
Python3
1657
Chapter 240. Program for Identity Matrix
C#
PHP
<?php
// PHP program to print
// Identity Matrix
function Identity($num)
{
$row; $col;
for ($row = 0; $row < $num; $row++)
1658
Chapter 240. Program for Identity Matrix
{
for ($col = 0; $col < $num; $col++)
{
// Checking if row is
// equal to column
if ($row == $col)
echo 1," ";
else
echo 0," ";
}
echo"\n";
}
return 0;
}
// Driver Code
$size = 5;
identity($size);
// This code is contributed by anuj_67.
?>
Output:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
C++
1659
Chapter 240. Program for Identity Matrix
{
for (int col = 0; col < N; col++)
{
if (row == col && mat[row][col] != 1)
return false;
else if (row != col && mat[row][col] != 0)
return false;
}
}
return true;
}
// Driver Code
int main()
{
int N = 4;
int mat[][MAX] = {{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}};
if (isIdentity(mat, N))
cout << "Yes ";
else
cout << "No ";
return 0;
}
Java
1660
Chapter 240. Program for Identity Matrix
}
// Driver Code
public static void main(String args[])
{
int N = 4;
int mat[][] = {{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}};
if (isIdentity(mat, N))
System.out.println("Yes ");
else
System.out.println("No ");
}
}
/*This code is contributed by Nikita Tiwari.*/
Python3
1661
Chapter 240. Program for Identity Matrix
C#
PHP
1662
Chapter 240. Program for Identity Matrix
<?php
// PHP program to check if a
// given matrix is identity
// $MAX = 100;
function isIdentity($mat, $N)
{
for ($row = 0; $row < $N; $row++)
{
for ( $col = 0; $col < $N; $col++)
{
if ($row == $col and
$mat[$row][$col] != 1)
return false;
else if ($row != $col &&
$mat[$row][$col] != 0)
return false;
}
}
return true;
}
// Driver Code
$N = 4;
$mat = array(array(1, 0, 0, 0),
array(0, 1, 0, 0),
array(0, 0, 1, 0),
array(0, 0, 0, 1));
if (isIdentity($mat, $N))
echo "Yes ";
else
echo "No ";
// This code is contributed by anuj_67.
?>
Output:
Yes
Source
https://www.geeksforgeeks.org/program-print-identity-matrix/
1663
Chapter 241
Input :
1 0 0
0.5 0 0.5
0 0 1
Output : yes
Explanation :
1664
Chapter 241. Program for 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++
1665
Chapter 241. Program for Markov matrix
// calls the function check()
if (checkMarkov(m))
cout << " yes ";
else
cout << " no ";
}
// This code is contributed by Anant Agarwal.
Java
1666
Chapter 241. Program for Markov matrix
Python3
C#
// C# code to check
// Markov Matrix
using System;
class GFG
{
static bool checkMarkov(double [,]m)
{
// outer loop to access
1667
Chapter 241. Program for Markov matrix
PHP
<?php
// PHP code to check Markov Matrix
function checkMarkov($m)
{
$n = 3;
1668
Chapter 241. Program for Markov matrix
// outer loop to access rows
// and inner to access columns
for ($i = 0; $i <$n; $i++)
{
// Find sum of current row
$sum = 0;
for ($j = 0; $j < $n; $j++)
$sum = $sum + $m[$i][$j];
if ($sum != 1)
return false;
}
return true;
}
// Driver Code
// Matrix to check
$m = array(array(0, 0, 1),
array(0.5, 0, 0.5),
array(1, 0, 0));
// calls the function check()
if (checkMarkov($m))
echo " yes ";
else
echo " no ";
// This code is contributed by nitin mittal.
?>
Output :
yes
Source
https://www.geeksforgeeks.org/markov-matrix/
1669
Chapter 242
Example:
In other words rank of A is the largest order of any non-zero minor in A where order of a
minor is the side-length of the square sub-matrix of which it is determinant.
1670
Chapter 242. Program for Rank of Matrix
So if M < N then maximum rank of A can be M else it can be N, in general rank of matrix
can’t be greater than min(M, N).
The rank of a matrix would be zero only if the matrix had no non-zero elements. If a matrix
had even one non-zero element, its minimum rank would be one.
How to find Rank?
The idea is based on conversion to Row echelon form.
Example:
row = 0:
Since mat[0][0] is not 0, we are in case 2.a of above algorithm.
We set all entries of 0'th column as 0 (except entry mat[0][0]).
To do this, we subtract R1*(-2) from R2, i.e., R2 --> R2 - R1*(-2)
mat[][] = {{10, 20, 10},
{ 0, 10, 30},
{30, 50, 0}}
And subtract R1*3 from R3, i.e., R3 --> R3 - R1*3
1671
Chapter 242. Program for Rank of Matrix
row = 1:
Since mat[1][1] is not 0, we are in case 2.a of above algorithm.
We set all entries of 1st column as 0 (except entry mat[1][1]).
To do this, we subtract R2*2 from R1, i.e., R1 --> R1 - R2*2
mat[][] = {{10, 0, -50},
{ 0, 10, 30},
{ 0, -10, -30}}
And subtract R2*(-1) from R3, i.e., R3 --> R3 - R2*(-1)
mat[][] = {{10, 0, -50},
{ 0, 10, 30},
{ 0, 0, 0}}
row = 2:
Since Since mat[2][2] is 0, we are in case 2.b of above algorithm.
Since there is no row below it swap. We reduce the rank by 1 and
keep row as 2.
The loop doesn't iterate next time because loop termination condition
row <= rank-1 returns false.
1672
Chapter 242. Program for Rank of Matrix
1673
Chapter 242. Program for Rank of Matrix
1674
Chapter 242. Program for Rank of Matrix
Java
1675
Chapter 242. Program for Rank of Matrix
int rank = C;
for (int row = 0; row < rank; row++)
{
// Before we visit current row
// 'row', we make sure that
// mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if (mat[row][row] != 0)
{
for (int col = 0; col < R; col++)
{
if (col != row)
{
// This makes all entries
// of current column
// as 0 except entry
// 'mat[row][row]'
double mult =
(double)mat[col][row] /
mat[row][row];
for (int i = 0; i < rank; i++)
mat[col][i] -= mult
* mat[row][i];
}
}
}
// Diagonal element is already zero.
// Two cases arise:
// 1) If there is a row below it
// with non-zero entry, then swap
// this row with that row and process
// that row
// 2) If all elements in current
// column below mat[r][row] are 0,
// then remvoe this column by
// swapping it with last column and
// reducing number of columns by 1.
else
{
boolean reduce = true;
1676
Chapter 242. Program for Rank of Matrix
1677
Chapter 242. Program for Rank of Matrix
+ rankOfMatrix(mat));
}
}
// This code is contributed by Anant Agarwal.
C#
1678
Chapter 242. Program for Rank of Matrix
int rank = C;
for (int row = 0; row < rank; row++)
{
// Before we visit current row
// 'row', we make sure that
// mat[row][0],....mat[row][row-1]
// are 0.
// Diagonal element is not zero
if (mat[row,row] != 0)
{
for (int col = 0; col < R; col++)
{
if (col != row)
{
// This makes all entries
// of current column
// as 0 except entry
// 'mat[row][row]'
double mult =
(double)mat[col,row] /
mat[row,row];
for (int i = 0; i < rank; i++)
mat[col,i] -= (int) mult
* mat[row,i];
}
}
}
// Diagonal element is already zero.
// Two cases arise:
// 1) If there is a row below it
// with non-zero entry, then swap
// this row with that row and process
// that row
// 2) If all elements in current
// column below mat[r][row] are 0,
// then remvoe this column by
// swapping it with last column and
// reducing number of columns by 1.
else
{
bool reduce = true;
1679
Chapter 242. Program for Rank of Matrix
1680
Chapter 242. Program for Rank of Matrix
+ rankOfMatrix(mat));
}
}
// This code is contributed by nitin mittal
Output:
Since above rank calculation method involves floating point arithmetic, it may produce
incorrect results if the division goes beyond precision. There are other methods to handle
Reference:
https://en.wikipedia.org/wiki/Rank_%28linear_algebra%29
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/program-for-rank-of-matrix/
1681
Chapter 243
1. In all 9 sub matrices 3×3 the elements should be 1-9, without repetition.
2. In all rows there should be elements between 1-9 , without repetition.
3. In all columns there should be elements between 1-9 , without repetition.
The task is to generate a 9 x 9 Suduku grid that is valid, i.e., a player can fill the grid
following above set of rules.
A simple naive solution can be.
3 8 5 0 0 0 0 0 0
9 2 1 0 0 0 0 0 0
6 4 7 0 0 0 0 0 0
0 0 0 1 2 3 0 0 0
0 0 0 7 8 4 0 0 0
0 0 0 6 9 5 0 0 0
1682
Chapter 243. Program for Sudoku Generator
0 0 0 0 0 0 8 7 3
0 0 0 0 0 0 9 6 2
0 0 0 0 0 0 1 4 5
(We can observe that in above matrix, the diagonal matrices are independent of other empty
matrices initially). So if we fill them first, then we will only have to do box check and thus
column/row check not required.
Secondly, while we fill rest of the non-diagonal elements, we will not have to use random
generator, but we can fill recursively by checking 1 to 9.
1683
Chapter 243. Program for Sudoku Generator
// Fill remaining blocks
fillRemaining(0, SRN);
// Remove Randomly K digits to make game
removeKDigits();
}
// Fill the diagonal SRN number of SRN x SRN matrices
void fillDiagonal()
{
for (int i = 0; i<N; i=i+SRN)
// for diagonal box, start coordinates->i==j
fillBox(i, i);
}
// Returns false if given 3 x 3 block contains num.
boolean unUsedInBox(int rowStart, int colStart, int num)
{
for (int i = 0; i<SRN; i++)
for (int j = 0; j<SRN; j++)
if (mat[rowStart+i][colStart+j]==num)
return false;
return true;
}
// Fill a 3 x 3 matrix.
void fillBox(int row,int col)
{
int num;
for (int i=0; i<SRN; i++)
{
for (int j=0; j<SRN; j++)
{
do
{
num = randomGenerator(N);
}
while (!unUsedInBox(row, col, num));
mat[row+i][col+j] = num;
}
}
}
1684
Chapter 243. Program for Sudoku Generator
1685
Chapter 243. Program for Sudoku Generator
j = SRN;
}
else if (i < N-SRN)
{
if (j==(int)(i/SRN)*SRN)
j = j + SRN;
}
else
{
if (j == N-SRN)
{
i = i + 1;
j = 0;
if (i>=N)
return true;
}
}
for (int num = 1; num<=N; num++)
{
if (CheckIfSafe(i, j, num))
{
mat[i][j] = num;
if (fillRemaining(i, j+1))
return true;
mat[i][j] = 0;
}
}
return false;
}
// Remove the K no. of digits to
// complete game
public void removeKDigits()
{
int count = K;
while (count != 0)
{
int cellId = randomGenerator(N*N);
// System.out.println(cellId);
// extract coordinates i and j
int i = (cellId/N);
int j = cellId%9;
if (j != 0)
j = j - 1;
1686
Chapter 243. Program for Sudoku Generator
2 3 0 4 1 5 0 6 8
0 8 0 2 3 6 5 1 9
1 6 0 9 8 7 2 3 4
3 1 7 0 9 4 0 2 5
4 5 8 1 2 0 6 9 7
9 2 6 0 5 8 3 0 1
0 0 0 5 0 0 1 0 2
0 0 0 8 4 2 9 0 3
5 9 2 3 7 1 4 8 6
Source
https://www.geeksforgeeks.org/program-sudoku-generator/
1687
Chapter 244
Input : 1 2 3
4 5 6
7 8 9
k = 4
Output : 4 8 12
16 20 24
28 32 36
The scalar multiplication of a number k(scalar), multiply it on every entry in the matrix.
and a matrix A is the matrix kA.
C++
1688
Chapter 244. Program for scalar multiplication of a matrix
#include <bits/stdc++.h>
using namespace std;
// Size of given matrix
#define N 3
void scalarProductMat(int mat[][N], int k)
{
// scalar element is multiplied by the matrix
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
mat[i][j] = mat[i][j] * k;
}
// Driver code
int main()
{
int mat[N][N] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int k = 4;
scalarProductMat(mat, k);
// to display the resultant matrix
printf("Scalar Product Matrix is : \n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
return 0;
}
Java
1689
Chapter 244. Program for scalar multiplication of a matrix
// scalar element is multiplied
// by the matrix
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
mat[i][j] = mat[i][j] * k;
}
// Driver code
public static void main (String[] args)
{
int mat[][] = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
int k = 4;
scalarProductMat(mat, k);
// to display the resultant matrix
System.out.println("Scalar Product Matrix is : ");
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
}
}
// This code is contributed by Ajit.
C#
// C# program to find
// the scalar product
// of a matrix
using System;
class GFG{
static int N = 3;
static void scalarProductMat(int[,] mat,
int k)
{
// scalar element is multiplied
// by the matrix
1690
Chapter 244. Program for scalar multiplication of a matrix
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-for-scalar-multiplication-of-a-matrix/
1691
Chapter 245
Program to Interchange
Diagonals of Matrix
Examples :
1692
Chapter 245. Program to Interchange Diagonals of Matrix
// C program to interchange
// the diagonals of matrix
#include<bits/stdc++.h>
using namespace std;
#define N 3
// Function to interchange diagonals
void interchangeDiagonals(int array[][N])
{
// swap elements of diagonal
for (int i = 0; i < N; ++i)
if (i != N / 2)
swap(array[i][i], array[i][N - i - 1]);
1693
Chapter 245. Program to Interchange Diagonals of Matrix
Java
1694
Chapter 245. Program to Interchange Diagonals of Matrix
C#
// C# program to interchange
// the diagonals of matrix
using System;
class GFG
{
public static int N = 3;
// Function to interchange diagonals
static void interchangeDiagonals(int [,]array)
{
// swap elements of diagonal
for (int i = 0; i < N; ++i)
if (i != N / 2)
{
int temp = array[i, i];
array[i, i] = array[i, N - i - 1];
array[i, N - i - 1] = temp;
}
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
Console.Write(array[i, j]+" ");
Console.WriteLine();
}
}
// Driver Code
public static void Main ()
{
int [,]array = { {4, 5, 6},
{1, 2, 3},
1695
Chapter 245. Program to Interchange Diagonals of Matrix
{7, 8, 9}
};
interchangeDiagonals(array);
}
}
// This code is contributed by vt_m.
Output:
6 5 4
1 2 3
9 8 7
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-to-interchange-diagonals-of-matrix/
1696
Chapter 246
Examples:
Input : mat[][] = {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output : 1 2 3 5 7 8 9
1697
Chapter 246. Program to Print Matrix in Z form
Complexity O(n)
We need to traverse first row of matrix then second diagonal and then last row.
CPP
1698
Chapter 246. Program to Print Matrix in Z form
// Print last row
for (int i = 1; i < n; i++)
cout << mat[n - 1][i] << " ";
}
// Driver function
int main()
{
int mat[][MAX] = { { 4, 5, 6, 8 },
{ 1, 2, 3, 1 },
{ 7, 8, 9, 4 },
{ 1, 8, 7, 5 } };
printZform(mat, 4);
return 0;
}
Java
1699
Chapter 246. Program to Print Matrix in Z form
Python3
1700
Chapter 246. Program to Print Matrix in Z form
C#
1701
Chapter 246. Program to Print Matrix in Z form
PHP
<?php
// PHP program to print a
// square matrix in Z form
$MAX = 100;
// Function to print a
// square matrix in Z form
function printZform( $mat, $n)
{
// print first row
for($i = 0; $i < $n; $i++)
echo $mat[0][$i] , " ";
// Print diagonal
$i = 1;$j = $n - 2;
// print diagonal
while ($i < $n and $j >= 0)
{
echo $mat[$i][$j] , " ";
$i++;
$j--;
}
// Print last row
for ( $i = 1; $i < $n; $i++)
echo $mat[$n - 1][$i] , " ";
}
// Driver Code
$mat = array(array(4, 5, 6, 8),
array(1, 2, 3, 1),
array(7, 8, 9, 4),
array(1, 8, 7, 5));
printZform($mat, 4);
// This code is contributed by anuj_67.
?>
Output:
4 5 6 8 3 8 1 8 7 5
1702
Chapter 246. Program to Print Matrix in Z form
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-print-matrix-z-form/
1703
Chapter 247
Examples:
C++
1704
Chapter 247. Program to check Involutory Matrix
1705
Chapter 247. Program to check Involutory Matrix
else
cout << "Not Involutory Matrix";
return 0;
}
Java
1706
Chapter 247. Program to check Involutory Matrix
C#
// C# Program to implement
// involutory matrix.
using System;
class GFG {
static int N = 3;
// Function for matrix multiplication.
static void multiply(int [,]mat, int [,]res)
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
res[i,j] = 0;
for (int k = 0; k < N; k++)
res[i,j] += mat[i,k] * mat[k,j];
}
}
}
// Function to check involutory matrix.
static bool InvolutoryMatrix(int [,]mat)
{
int [,]res = new int[N,N];
1707
Chapter 247. Program to check Involutory Matrix
PHP
<?php
// Program to implement
// involutory matrix.
$N = 3;
// Function for matrix
// multiplication.
function multiply($mat, $res)
{
1708
Chapter 247. Program to check Involutory Matrix
global $N;
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
{
$res[$i][$j] = 0;
for ($k = 0; $k < $N; $k++)
$res[$i][$j] += $mat[$i][$k] *
$mat[$k][$j];
}
}
return $res;
}
// Function to check
// involutory matrix.
function InvolutoryMatrix($mat)
{
global $N;
$res;
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
$res[$i][$j] = 0;
// multiply function call.
$res = multiply($mat, $res);
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
{
if ($i == $j &&
$res[$i][$j] != 1)
return false;
if ($i != $j &&
$res[$i][$j] != 0)
return false;
}
}
return true;
}
// Driver Code
$mat = array(array(1, 0, 0),
array(0, -1, 0),
array(0, 0, -1));
// Function call. If function
1709
Chapter 247. Program to check Involutory Matrix
Output :
Involutory Matrix
Source
https://www.geeksforgeeks.org/program-check-involutory-matrix/
1710
Chapter 248
Input :
Mat[4][0] = {{4, 0, 0, 0},
{0, 5, 0, 0},
{0, 0, 2, 0},
{0, 0, 0, 1}}
Output : Yes
CPP
1711
Chapter 248. Program to check diagonal matrix and scalar matrix
Java
1712
Chapter 248. Program to check diagonal matrix and scalar matrix
Python3
1713
Chapter 248. Program to check diagonal matrix and scalar matrix
(mat[i][j] != 0)) :
return False
return True
# Driver function
mat = [[ 4, 0, 0, 0 ],
[ 0, 7, 0, 0 ],
[ 0, 0, 5, 0 ],
[ 0, 0, 0, 1 ]]
if (isDiagonalMatrix(mat)) :
print("Yes")
else :
print("No")
# This code is contributed by Nikita Tiwari.
C#
1714
Chapter 248. Program to check diagonal matrix and scalar matrix
PHP
<?php
// Program to check matrix is
// diagonal matrix or not.
$N= 4;
// Function to check matrix is
// diagonal matrix or not.
function isDiagonalMatrix($mat)
{
global $N;
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
// condition to check
// other elements
// except main diagonal
// are zero or not.
if (($i != $j) &&
($mat[$i][$j] != 0))
return false;
return true;
}
// Driver Code
$mat = array(array(4, 0, 0, 0),
array(0, 7, 0, 0),
array(0, 0, 5, 0),
1715
Chapter 248. Program to check diagonal matrix and scalar matrix
array(0, 0, 0, 1));
if (isDiagonalMatrix($mat))
echo "Yes" ,"\n";
else
echo "No","\n";
// This code is contributed by jit_t
?>
Output:
Yes
Scalar matrix:
A square matrix is said to be scalar matrix if all the main diagonal elements are equal and
other elements except main diagonal are zero. Scalar matrix can also be written in form of
n * I, where n is any real number and I is the identity matrix.
Examples:
Input :
Mat[4][4] = {{4, 0, 0, 0},
{0, 4, 0, 0},
{0, 0, 4, 0},
{0, 0, 0, 4}}
Output : Yes
CPP
1716
Chapter 248. Program to check diagonal matrix and scalar matrix
Java
1717
Chapter 248. Program to check diagonal matrix and scalar matrix
return false;
// Check all diagonal elements
// are same or not.
for (int i = 0; i < N - 1; i++)
if (mat[i][i] != mat[i + 1][i + 1])
return false;
return true;
}
// Driver function
public static void main(String args[])
{
int mat[ ][ ] = { { 2, 0, 0, 0 },
{ 0, 2, 0, 0 },
{ 0, 0, 2, 0 },
{ 0, 0, 0, 2 } };
// Function call
if (isScalarMatrix(mat))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed
// by Nikita tiwari.
Python3
1718
Chapter 248. Program to check diagonal matrix and scalar matrix
# Check all diagonal
# elements are same or not.
for i in range(0,N-1) :
if (mat[i][i] !=
mat[i + 1][i + 1]) :
return False
return True
# Driver function
mat = [[ 2, 0, 0, 0 ],
[ 0, 2, 0, 0 ],
[ 0, 0, 2, 0 ],
[ 0, 0, 0, 2 ]]
# Function call
if (isScalarMatrix(mat)):
print("Yes")
else :
print("No")
# This code is contributed by
# Nikita tiwari.
C#
1719
Chapter 248. Program to check diagonal matrix and scalar matrix
// Check all diagonal elements
// are same or not.
for (int i = 0; i < N - 1; i++)
if (mat[i, i] != mat[i + 1, i + 1])
return false;
return true;
}
// Driver function
public static void Main()
{
int [,]mat = { { 2, 0, 0, 0 },
{ 0, 2, 0, 0 },
{ 0, 0, 2, 0 },
{ 0, 0, 0, 2 } };
// Function call
if (isScalarMatrix(mat))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by vt_m.
PHP
<?php
// Program to check matrix
// is scalar matrix or not.
$N = 4;
// Function to check matrix
// is scalar matrix or not.
function isScalarMatrix($mat)
{
global $N;
// Check all elements except
// main diagonal are zero or not.
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
if (($i != $j) &&
($mat[$i][$j] != 0))
return false;
1720
Chapter 248. Program to check diagonal matrix and scalar matrix
Output :
Yes
Source
https://www.geeksforgeeks.org/program-check-diagonal-matrix-scalar-matrix/
1721
Chapter 249
Examples:
C++
1722
Chapter 249. Program to check idempotent matrix
1723
Chapter 249. Program to check idempotent matrix
return 0;
}
Java
1724
Chapter 249. Program to check idempotent matrix
Python 3
1725
Chapter 249. Program to check idempotent matrix
return False
return True
# driver Function
mat = [ [2, -2, -4],
[-1, 3, 4],
[1, -2, -3] ]
# checkIdempotent function call.
if (checkIdempotent(mat)):
print("Idempotent Matrix")
else:
print("Not Idempotent Matrix.")
# This code is contributed by Gitanjali.
C#
1726
Chapter 249. Program to check idempotent matrix
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (mat[i,j] != res[i,j])
return false;
}
}
return true;
}
// Driver code
public static void Main ()
{
int [,]mat = {{2, -2, 4},
{-1, 3, 4},
{1, -2, -3}};
// checkIdempotent function call.
if (checkIdempotent(mat))
Console.WriteLine( "Idempotent Matrix");
else
Console.WriteLine("Not Idempotent Matrix.");
}
}
// This code is contributed by vt_m.
Output
Idempotent Matrix
Source
https://www.geeksforgeeks.org/program-check-idempotent-matrix/
1727
Chapter 250
Input : 1 2 3
2 1 4
3 4 3
Output : Yes
Input : 3 5 8
3 4 7
8 5 3
Output : No
C++
1728
Chapter 250. Program to check if a matrix is symmetric
const int MAX = 100;
// Fills transpose of mat[N][N] in tr[N][N]
void transpose(int mat[][MAX], int tr[][MAX], int N)
{
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
tr[i][j] = mat[j][i];
}
// Returns true if mat[N][N] is symmetric, else false
bool isSymmetric(int mat[][MAX], int N)
{
int tr[N][MAX];
transpose(mat, tr, N);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] != tr[i][j])
return false;
return true;
}
// Driver code
int main()
{
int mat[][MAX] = { { 1, 3, 5 },
{ 3, 2, 4 },
{ 5, 4, 1 } };
if (isSymmetric(mat, 3))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
1729
Chapter 250. Program to check if a matrix is symmetric
Python
1730
Chapter 250. Program to check if a matrix is symmetric
# Returns true if mat[N][N] is symmetric, else false
def isSymmetric(mat, N):
tr = [ [0 for j in range(len(mat[0])) ] for i in range(len(mat)) ]
transpose(mat, tr, N)
for i in range(N):
for j in range(N):
if (mat[i][j] != tr[i][j]):
return False
return True
# Driver code
mat = [ [ 1, 3, 5 ], [ 3, 2, 4 ], [ 5, 4, 1 ] ]
if (isSymmetric(mat, 3)):
print "Yes"
else:
print "No"
# This code is contributed by Sachin Bisht
C#
1731
Chapter 250. Program to check if a matrix is symmetric
return false;
return true;
}
// Driver code
public static void Main ()
{
int [,]mat = { { 1, 3, 5 },
{ 3, 2, 4 },
{ 5, 4, 1 } };
if (isSymmetric(mat, 3))
Console.WriteLine( "Yes");
else
Console.WriteLine( "No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// Simple PHP code for check a matrix is
// symmetric or not.
// Returns true if mat[N][N] is
// symmetric, else false
function isSymmetric($mat, $N)
{
$tr = array(array());
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
$tr[$i][$j] = $mat[$j][$i];
// Fills transpose of
// mat[N][N] in tr[N][N]
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
if ($mat[$i][$j] != $tr[$i][$j])
return false;
return true;
}
// Driver code
$mat= array(array(1, 3, 5),
1732
Chapter 250. Program to check if a matrix is symmetric
array(3, 2, 4),
array(5, 4, 1));
if (isSymmetric($mat, 3))
echo "Yes";
else
echo "No";
// This code is contributed by Sam007
?>
Output :
Yes
C++
1733
Chapter 250. Program to check if a matrix is symmetric
if (isSymmetric(mat, 3))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
1734
Chapter 250. Program to check if a matrix is symmetric
Python
C#
1735
Chapter 250. Program to check if a matrix is symmetric
int [,]mat = { { 1, 3, 5 },
{ 3, 2, 4 },
{ 5, 4, 1 } };
if (isSymmetric(mat, 3))
Console.WriteLine( "Yes");
else
Console.WriteLine("NO");
}
}
// This code is contributed by vt_m.
PHP
<?php
// Efficient PHP code for
// check a matrix is
// symmetric or not.
$MAX = 100;
// Returns true if mat[N][N]
// is symmetric, else false
function isSymmetric($mat, $N)
{
for ($i = 0; $i < $N; $i++)
for ($j = 0; $j < $N; $j++)
if ($mat[$i][$j] != $mat[$j][$i])
return false;
return true;
}
// Driver code
$mat = array(array(1, 3, 5),
array(3, 2, 4),
array(5, 4, 1));
if (isSymmetric($mat, 3))
echo("Yes");
else
echo("No");
// This code is contributed by Ajit.
?>
1736
Chapter 250. Program to check if a matrix is symmetric
Output:
Yes
Source
https://www.geeksforgeeks.org/program-to-check-if-a-matrix-is-symmetric/
1737
Chapter 251
Examples:
1738
Chapter 251. Program to check if matrix is lower triangular
C++
Java
1739
Chapter 251. Program to check if matrix is lower triangular
Python3
1740
Chapter 251. Program to check if matrix is lower triangular
[4,6,2,0],
[0,4,7,6]]
if islowertriangular(M):
print ("Yes")
else:
print ("No")
# This code is contributed by Anurag Rawat
C#
1741
Chapter 251. Program to check if matrix is lower triangular
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to check lower
// triangular matrix.
$N = 4;
// Function to check matrix is in
// lower triangular form or not.
function isLowerTriangularMatrix($mat)
{
global $N;
for ($i = 0; $i < $N; $i++)
for ($j = $i + 1; $j < $N; $j++)
if ($mat[$i][$j] != 0)
return false;
return true;
}
// Driver Code
$mat = array(array( 1, 0, 0, 0 ),
array( 1, 4, 0, 0 ),
array( 4, 6, 2, 0 ),
array( 0, 4, 7, 6 ));
// Function call
if (isLowerTriangularMatrix($mat))
echo("Yes");
else
echo("No");
// This code is contributed by Ajit.
?>
Output:
Yes
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-check-matrix-lower-triangular/
1742
Chapter 252
Input : 0 0 0
4 5 6
1 2 3
Output : Yes
Determinant value of the matrix is
0 (Note first row is 0)
Input : 1 0 0
4 5 6
1 2 3
Output : No
Determinant value of the matrix is 3
(which is non-zero).
First find the determinant of the matrix and the check the condition if the determinant id
0 or not, if it is 0 then matrix is a singular matrix otherwise it is a non-singular matrix .
C++
1743
Chapter 252. Program to check if matrix is singular or not
1744
Chapter 252. Program to check if matrix is singular or not
Output:
Matrix is non-singular
Source
https://www.geeksforgeeks.org/program-check-matrix-singular-not/
1745
Chapter 253
Examples:
1746
Chapter 253. Program to check if matrix is upper triangular
{0, 0, 2, 5},
{0, 0, 0, 6}};
Output : Matrix is in Upper Triangular form.
C++
Java
1747
Chapter 253. Program to check if matrix is upper triangular
import java.lang.*;
public class GfG
{
private static final int N = 4;
// Function to check matrix is in
// upper triangular form or not.
public static Boolean isUpperTriangularMatrix(int mat[][])
{
for (int i = 1; i < N ; i++)
for (int j = 0; j < i; j++)
if (mat[i][j] != 0)
return false;
return true;
}
// driver function
public static void main(String argc[]){
int[][] mat= { { 1, 3, 5, 3 },
{ 0, 4, 6, 2 },
{ 0, 0, 2, 5 },
{ 0, 0, 0, 6 } };
if (isUpperTriangularMatrix(mat))
System.out.println("Yes");
else
System.out.println("No");
}
}
/* This code is contributed by Sagar Shukla */
Python3
1748
Chapter 253. Program to check if matrix is upper triangular
M = [[1,3,5,3],
[0,4,6,2],
[0,0,2,5],
[0,0,0,6]]
if isuppertriangular(M):
print ("Yes")
else:
print ("No")
# This code is contributed by Anurag Rawat
C#
1749
Chapter 253. Program to check if matrix is upper triangular
PHP
<?php
// PHP Program to check upper
// triangular matrix.
$N = 4;
// Function to check matrix is
// in upper triangular form or
// not.
function isUpperTriangularMatrix($mat)
{
global $N;
for ($i = 1; $i < $N; $i++)
for ($j = 0; $j < $i; $j++)
if ($mat[$i][$j] != 0)
return false;
return true;
}
// Driver Code
$mat = array(array(1, 3, 5, 3),
array(0, 4, 6, 2) ,
array(0, 0, 2, 5),
array(0, 0, 0, 6));
if (isUpperTriangularMatrix($mat))
echo "Yes";
else
echo"No";
// This code is contributed by anuj_67.
?>
Output:
Yes
Improved By : vt_m
Source
https://www.geeksforgeeks.org/program-check-matrix-upper-triangular/
1750
Chapter 254
#include <stdio.h>
#define N 4
// This function returns 1 if A[][] and B[][] are identical
// otherwise returns 0
int areSame(int A[][N], int B[][N])
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
if (A[i][j] != B[i][j])
return 0;
return 1;
}
int main()
{
int A[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
1751
Chapter 254. Program to check if two given matrices are identical
Java
1752
Chapter 254. Program to check if two given matrices are identical
Python3
C#
1753
Chapter 254. Program to check if two given matrices are identical
PHP
<?php
// PHP Program to check if two
1754
Chapter 254. Program to check if two given matrices are identical
Output:
The program can be extended for rectangular matrices. The following post can be useful
for extending this program.
1755
Chapter 254. Program to check if two given matrices are identical
Source
https://www.geeksforgeeks.org/program-to-check-if-two-given-matrices-are-identical/
1756
Chapter 255
1757
Chapter 255. Program to find Normal and Trace of a matrix
CPP
1758
Chapter 255. Program to find Normal and Trace of a matrix
int sum = 0;
for (int i=0; i<n; i++)
sum += mat[i][i];
return sum;
}
// Driven source
int main()
{
int mat[][MAX] = {{1, 1, 1, 1, 1},
{2, 2, 2, 2, 2},
{3, 3, 3, 3, 3},
{4, 4, 4, 4, 4},
{5, 5, 5, 5, 5},
};
cout << "Trace of Matrix = "
<< findTrace(mat, 5) << endl;
cout << "Normal of Matrix = "
<< findNormal(mat, 5) << endl;
return 0;
}
Java
1759
Chapter 255. Program to find Normal and Trace of a matrix
C#
1760
Chapter 255. Program to find Normal and Trace of a matrix
PHP
<?php
// PHP program to find trace and
// normal of given matrix
// Size of given matrix
$MAX = 100;
// Returns Normal of a
// matrix of size n x n
function findNormal($mat, $n)
{
$sum = 0;
for ( $i = 0; $i < $n; $i++)
for ( $j = 0; $j < $n; $j++)
$sum += $mat[$i][$j] *
$mat[$i][$j];
1761
Chapter 255. Program to find Normal and Trace of a matrix
return floor(sqrt($sum));
}
// Returns trace of a
// matrix of size n x n
function findTrace( $mat, $n)
{
$sum = 0;
for ( $i = 0; $i < $n; $i++)
$sum += $mat[$i][$i];
return $sum;
}
// Driver Code
$mat = array(array(1, 1, 1, 1, 1),
array(2, 2, 2, 2, 2),
array(3, 3, 3, 3, 3),
array(4, 4, 4, 4, 4),
array(5, 5, 5, 5, 5));
echo "Trace of Matrix = ",
findTrace($mat, 5),"\n";
echo "Normal of Matrix = " ,
findNormal($mat, 5) ;
// This code is contributed by anuj_67.
?>
Output :
Trace of matrix = 15
Normal of matrix = 16
Source
https://www.geeksforgeeks.org/program-find-normal-trace-matrix/
1762
Chapter 256
Input : R = 1 C = 0
Output : Row Matrix
Input : R = 4 C = 5
Output : Horizontal Matrix
C++
1763
Chapter 256. Program to find all types of Matrix
#include <bits/stdc++.h>
using namespace std;
// Fuction to display which
// type of matrix
void check(int r, int c)
{
if (r == 0 && c == 1)
cout << "Column Matrix " << endl;
else if (r == 1 && c == 0)
cout << "Row Matrix " << endl;
else if (r < c)
cout << "Horizontal Matrix " << endl;
else if (r > c)
cout << "Vertical Matrix " << endl;
else if (r == c)
cout << "Square Matrix " << endl;
}
// Driver code
int main()
{
// input for r and c
// function calling
check(1, 0);
check(0, 1);
check(4, 5);
check(5, 4);
check(3, 3);
return 0;
}
Java
1764
Chapter 256. Program to find all types of Matrix
Python3
1765
Chapter 256. Program to find all types of Matrix
elif r == c:
print ("Square Matrix ")
# Driver code
check(1, 0)
check(0, 1)
check(4, 5)
check(5, 4)
check(3, 3)
# This code is contributed by Sam007.
C#
1766
Chapter 256. Program to find all types of Matrix
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to check
// types of Matrix
// Fuction to display which
// type of matrix
function check($r, $c)
{
if ($r == 0 && $c == 1)
echo "Column Matrix "."\n";
else if ($r == 1 && $c == 0)
echo "Row Matrix "."\n";
else if ($r < $c)
echo "Horizontal Matrix "."\n";
else if ($r > $c)
echo "Vertical Matrix "."\n";
else if ($r == $c)
echo "Square Matrix "."\n";
}
// Driver code
// input for r and c
// function calling
check(1, 0);
check(0, 1);
check(4, 5);
check(5, 4);
check(3, 3);
// This code is contributed by Sam007
?>
Output :
Row Matrix
Column Matrix
Horizontal Matrix
Vertical Matrix
Square Matrix
1767
Chapter 256. Program to find all types of Matrix
Improved By : Sam007
Source
https://www.geeksforgeeks.org/program-to-find-all-types-of-matrix/
1768
Chapter 257
The solution is to initialize max as first element, then traverse the given array from second
element till end. For every traversed element, compare it with max, if it is greater than
max, then update max.
C++
1769
Chapter 257. Program to find largest element in an array
1770
Chapter 257. Program to find largest element in an array
{
int arr[] = {10, 324, 45, 90, 9808};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Largest in given array is %d", largest(arr, n));
return 0;
}
Java
Python3
1771
Chapter 257. Program to find largest element in an array
C#
1772
Chapter 257. Program to find largest element in an array
PHP
<?php
// PHP program to find maximum
// in arr[] of size n
// PHP function to find maximum
// in arr[] of size n
function largest($arr, $n)
{
$i;
// Initialize maximum element
$max = $arr[0];
// Traverse array elements
// from second and
// compare every element
// with current max
for ($i = 1; $i < $n; $i++)
if ($arr[$i] > $max)
$max = $arr[$i];
return $max;
}
// Driver Code
$arr= array(10, 324, 45, 90, 9808);
$n = sizeof($arr);
echo "Largest in given array is "
, largest($arr, $n);
// This code is contributed by aj_36
?>
Output:
1773
Chapter 257. Program to find largest element in an array
Java
1774
Chapter 257. Program to find largest element in an array
int n = arr.length;
System.out.println(largest(arr, n));
}
}
// This code is contributed
// by anuj_67.
Python3
C#
1775
Chapter 257. Program to find largest element in an array
int n = arr.Length;
Console.WriteLine( largest(arr, n));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find maximum
// in arr[] of size n
// returns maximum in
// arr[] of size n
function largest( $arr, $n)
{
return max($arr);
}
// Driver COde
$arr = array(10, 324, 45, 90, 9808);
$n = count($arr);
echo largest($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
9808
Source
https://www.geeksforgeeks.org/c-program-find-largest-element-array/
1776
Chapter 258
C++
#include <stdio.h>
#define N 4
// This function stores transpose of A[][] in B[][]
1777
Chapter 258. Program to find transpose of a matrix
Java
1778
Chapter 258. Program to find transpose of a matrix
// Driver code
public static void main (String[] args)
{
int A[][] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int B[][] = new int[N][N], i, j;
transpose(A, B);
System.out.print("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
System.out.print(B[i][j] + " ");
System.out.print("\n");
}
}
}
// This code is contributed by Anant Agarwal.
Python3
1779
Chapter 258. Program to find transpose of a matrix
C#
// C# Program to find
// transpose of a matrix
using System;
class GFG
{
static int N = 4;
// This function stores transpose
// of A[][] in B[][]
static void transpose(int [,]A, int [,]B)
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
B[i,j] = A[j,i];
}
// Driver code
public static void Main ()
{
int [,]A = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int [,]B = new int[N,N];
// Function calling
transpose(A, B);
Console.Write("Result matrix is \n");
for (int i = 0; i < N; i++)
1780
Chapter 258. Program to find transpose of a matrix
{
for (int j = 0; j < N; j++)
Console.Write(B[i,j] + " ");
Console.Write("\n");
}
}
}
// This code is contributed by nitin mittal.
Output:
Result matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
#include <stdio.h>
#define M 3
#define N 4
// This function stores transpose of A[][] in B[][]
void transpose(int A[][N], int B[][M])
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
B[i][j] = A[j][i];
}
int main()
{
int A[M][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}};
// Note dimensions of B[][]
int B[N][M], i, j;
transpose(A, B);
1781
Chapter 258. Program to find transpose of a matrix
printf("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
printf("%d ", B[i][j]);
printf("\n");
}
return 0;
}
Java
1782
Chapter 258. Program to find transpose of a matrix
System.out.print("\n");
}
}
}
// This code is contributed by Anant Agarwal.
Python3
C#
// C# Program to find
// transpose of a matrix
using System;
class GFG {
1783
Chapter 258. Program to find transpose of a matrix
static int M = 3;
static int N = 4;
// This function stores transpose
// of A[][] in B[][]
static void transpose(int [,]A, int [,]B)
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
B[i,j] = A[j,i];
}
// Driver code
public static void Main ()
{
int [,]A = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3}};
int [,]B= new int[N,M];
transpose(A, B);
Console.WriteLine("Result matrix is \n");
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
Console.Write(B[i,j] + " ");
Console.Write("\n");
}
}
}
// This code is contributed by nitin mittal
Output:
Result matrix is
1 2 3
1 2 3
1 2 3
1 2 3
1784
Chapter 258. Program to find transpose of a matrix
C++
#include <bits/stdc++.h>
using namespace std;
#define N 4
// Converts A[][] to its transpose
void transpose(int A[][N])
{
for (int i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
swap(A[i][j], A[j][i]);
}
int main()
{
int A[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
transpose(A);
printf("Modified matrix is \n");
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf("%d ", A[i][j]);
printf("\n");
}
return 0;
}
Java
1785
Chapter 258. Program to find transpose of a matrix
Python3
1786
Chapter 258. Program to find transpose of a matrix
transpose(A)
print("Modified matrix is")
for i in range(N):
for j in range(N):
print(A[i][j], " ", end='')
print()
# This code is contributed
# by Anant Agarwal.
C#
1787
Chapter 258. Program to find transpose of a matrix
Output:
Modified matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Source
https://www.geeksforgeeks.org/program-to-find-transpose-of-a-matrix/
1788
Chapter 259
1789
Chapter 259. Program to multiply two matrices
1790
Chapter 259. Program to multiply two matrices
{
int i, j, k;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
res[i][j] = 0;
for (k = 0; k < N; k++)
res[i][j] += mat1[i][k]*mat2[k][j];
}
}
}
int main()
{
int mat1[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int mat2[N][N] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int res[N][N]; // To store result
int i, j;
multiply(mat1, mat2, res);
printf("Result matrix is \n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%d ", res[i][j]);
printf("\n");
}
return 0;
}
Java
1791
Chapter 259. Program to multiply two matrices
static int N = 4;
// This function multiplies mat1[][]
// and mat2[][], and stores the result
// in res[][]
static void multiply(int mat1[][],
int mat2[][], int res[][])
{
int i, j, k;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
res[i][j] = 0;
for (k = 0; k < N; k++)
res[i][j] += mat1[i][k]
* mat2[k][j];
}
}
}
// Driver code
public static void main (String[] args)
{
int mat1[][] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int mat2[][] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
// To store result
int res[][] = new int[N][N] ;
int i, j;
multiply(mat1, mat2, res);
System.out.println("Result matrix"
+ " is ");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
System.out.print( res[i][j]
+ " ");
System.out.println();
1792
Chapter 259. Program to multiply two matrices
}
}
}
// This code is contributed by anuj_67.
C#
1793
Chapter 259. Program to multiply two matrices
// To store result
int [,]res = new int[N,N] ;
int i, j;
multiply(mat1, mat2, res);
Console.WriteLine("Result matrix"
+ " is ");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
Console.Write( res[i,j]
+ " ");
Console.WriteLine();
}
}
}
// This code is contributed by anuj_67.
Output:
Result matrix is
10 10 10 10
20 20 20 20
30 30 30 30
40 40 40 40
1794
Chapter 259. Program to multiply two matrices
int res[m1][n2];
for (i = 0; i < m1; i++) {
for (j = 0; j < n2; j++) {
res[i][j] = 0;
for (x = 0; x < m2; x++) {
*(*(res + i) + j) += *(*(mat1 + i) + x) *
*(*(mat2 + x) + j);
}
}
}
for (i = 0; i < m1; i++) {
for (j = 0; j < n2; j++) {
printf("%d ", *(*(res + i) + j));
}
printf("\n");
}
}
// Driver code
int main()
{
int mat1[][2] = { { 2, 4 }, { 3, 4 } };
int mat2[][2] = { { 1, 2 }, { 1, 3 } };
int m1 = 2, m2 = 2, n1 = 2, n2 = 2;
multiply(m1, m2, mat1, n1, n2, mat2);
return 0;
}
Output:
6 16
7 18
The time complexity of the above program is O(n3 ). It can be optimized using Strassen’s
Matrix Multiplication
Improved By : vt_m, SoumikMondal
Source
https://www.geeksforgeeks.org/c-program-multiply-two-matrices/
1795
Chapter 260
Program to print Lower triangular and Upper triangular matrix of an array - GeeksforGeeks
Prerequisite – Multidimensional Arrays in C / C++
Given a two dimensional array, Write a program to print lower triangular matrix and upper
triangular matrix.
• Lower triangular matrix is a matrix which contain elements below principle diagonal
including principle diagonal elements and rest of the elements are 0.
• Upper triangular matrix is a matrix which contain elements above principle diagonal
including principle diagonal elements and rest of the elements are 0.
LOWER TRIANGULAR :
1796
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
UPPER TIRANGULAR :
Examples :
Input : matrix[3][3] = {1 2 3
4 5 6
7 8 9}
1797
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
Output :
Lower : 1 0 0 Upper : 1 2 3
4 5 0 0 5 6
7 8 9 0 0 9
Input : matrix[3][3] = {7 8 9
3 2 1
6 5 4}
Output :
Lower : 7 0 0 Upper : 7 8 9
3 2 0 0 2 1
6 5 4 0 0 4
Steps:
1. For lower triangular matrix, we check the index position i and j i.e row and column
respectively. If column position is greater than row position we simply make that
position 0.
2. For upper triangular matrix, we check the index position i and j i.e row and column
respectively. If column position is smaller than row position we simply make that
position 0.
C++
1798
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
Java
1799
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
1800
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
C#
// C# program to print
// Lower triangular and
// Upper triangular
// matrix of an array
using System;
class GFG
{
// method to form lower
// triangular matrix
static void lower(int [,]matrix,
int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (i < j)
{
Console.Write("0" + " ");
}
else
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
// Method to form upper
// triangular matrix
static void upper(int [,]matrix,
int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
1801
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
{
for (j = 0; j < col; j++)
{
if (i > j)
{
Console.Write("0" + " ");
}
else
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
// Driver Code
static public void Main ()
{
int [,]matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int row = 3, col = 3;
Console.WriteLine("Lower triangular matrix: ");
lower(matrix, row, col);
Console.WriteLine("Upper triangular matrix: ");
upper(matrix, row, col);
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to print Lower
// triangular and Upper triangular
// matrix of an array
// Function to form
// lower triangular matrix
function lower($matrix, $row, $col)
{
$i; $j;
for ($i = 0; $i < $row; $i++)
{
for ($j = 0; $j < $col; $j++)
{
1802
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
Output :
1803
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-print-lower-triangular-upper-triangular-matrix-array/
1804
Chapter 261
Input : 5
Output :
- -
|
- -
|
- -
Input : 8
Output :
- -
| |
- -
| |
- -
Explanation:
Take a matrix of size 5*5 and store 0 and 1 in the matrix. If matrix cell is 0 then it is used
for space and if matrix cell is 1 then it is used either for horizontal or vertical line.
If row number is even then print the horizontal (-) line and if row number is odd then print
the vertical ( | ) line.
1805
Chapter 261. Program to print numbers in digital form
C++
1806
Chapter 261. Program to print numbers in digital form
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
void digit2()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
void digit3()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
void digit4()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
void digit5()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
1807
Chapter 261. Program to print numbers in digital form
print(mat);
}
void digit6()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
void digit7()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
void digit8()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
void digit9()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[5][5] = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
// Function to check number
1808
Chapter 261. Program to print numbers in digital form
1809
Chapter 261. Program to print numbers in digital form
// function call to check digit
checkDigit(num);
return 0;
}
Java
1810
Chapter 261. Program to print numbers in digital form
}
static void digit1()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[][] = { { 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
static void digit2()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[][] = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit3()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[][] = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit4()
{
// In matrix 0 used for space
// and 1 for either - or |
int mat[][] = { { 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
static void digit5()
{
// In matrix 0 used for space
1811
Chapter 261. Program to print numbers in digital form
1812
Chapter 261. Program to print numbers in digital form
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
// Function to check number
static void checkDigit(int num)
{
// for digit 0
if (num == 0)
digit0();
// for digit 1
else if (num == 1)
digit1();
// for digit 2
else if (num == 2)
digit2();
// for digit 3
else if (num == 3)
digit3();
// for digit 4
else if (num == 4)
digit4();
// for digit 5
else if (num == 5)
digit5();
// for digit 6
else if (num == 6)
digit6();
// for digit 7
else if (num == 7)
digit7();
// for digit 8
else if (num == 8)
digit8();
// for digit 9
else if (num == 9)
digit9();
}
1813
Chapter 261. Program to print numbers in digital form
// Driver program
public static void main (String[] args)
{
// Input a number
int num = 9;
// function call to check digit
checkDigit(num);
}
}
// This code is contributed by vt_m.
C#
// C# profgram to print
// number in digital form
using System;
class GFG {
// Function to print numbers
static void print(int [,]mat)
{
// If in matrix row number is even
// then print "-" otherwise print "|"
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i % 2 == 0) {
if (mat[i,j] == 1)
Console.Write("-");
else
Console.Write(" ");
}
else {
if (mat[i,j] == 1)
Console.Write("|");
else
Console.Write(" ");
}
}
Console.WriteLine();
}
}
1814
Chapter 261. Program to print numbers in digital form
static void digit0()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit1()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
static void digit2()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit3()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
1815
Chapter 261. Program to print numbers in digital form
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit4()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 0, 0, 0, 0 } };
print(mat);
}
static void digit5()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit6()
{
// In matrix 0 used for space
// and 1 for either - or |
int [ ,]mat = { { 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 1, 0, 0, 0, 1 },
{ 0, 1, 0, 1, 0 } };
print(mat);
}
static void digit7()
{
// In matrix 0 used for space
1816
Chapter 261. Program to print numbers in digital form
1817
Chapter 261. Program to print numbers in digital form
else if (num == 2)
digit2();
// for digit 3
else if (num == 3)
digit3();
// for digit 4
else if (num == 4)
digit4();
// for digit 5
else if (num == 5)
digit5();
// for digit 6
else if (num == 6)
digit6();
// for digit 7
else if (num == 7)
digit7();
// for digit 8
else if (num == 8)
digit8();
// for digit 9
else if (num == 9)
digit9();
}
// Driver program
public static void Main ()
{
// Input a number
int num = 9;
// function call to check digit
checkDigit(num);
}
}
// This code is contributed by vt_m.
PHP
1818
Chapter 261. Program to print numbers in digital form
<?php
// PHP implementation to print
// number in digital form
// Function to print numbers
function printnum(array $mat)
{
// If in matrix row number is even
// then print "-" otherwise print "|"
for ($i = 0; $i < 5; $i++)
{
for ($j = 0; $j < 5; $j++)
{
if ($i % 2 == 0)
{
if ($mat[$i][$j] == 1)
echo "-";
else
echo " ";
}
else
{
if ($mat[$i][$j] == 1)
echo "|";
else
echo " ";
}
}
echo "\n";
}
}
function digit0()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat= array(array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 0, 0, 0, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
function digit1()
{
// In matrix 0 used for space
// and 1 for either - or |
1819
Chapter 261. Program to print numbers in digital form
$mat = array(array( 0, 0, 0, 0, 0 ),
array( 0, 0, 1, 0, 0 ),
array( 0, 0, 0, 0, 0 ),
array( 0, 0, 1, 0, 0 ),
array( 0, 0, 0, 0, 0 ));
printnum($mat);
}
function digit2()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat= array(array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 0 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
function digit3()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat= array(array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
function digit4()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat= array(array( 0, 0, 0, 0, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 0, 0, 0, 0 ));
printnum($mat);
}
function digit5()
{
// In matrix 0 used for space
// and 1 for either - or |
1820
Chapter 261. Program to print numbers in digital form
$mat = array(array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 0 ),
array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
function digit6()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat = array(array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 0 ),
array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
function digit7()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat = array(array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 0, 0, 0, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 0, 0, 0, 0 ) );
printnum($mat);
}
function digit8()
{
// In matrix 0 used for space
// and 1 for either - or |
$mat = array(array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
function digit9()
{
// In matrix 0 used for space
// and 1 for either - or |
1821
Chapter 261. Program to print numbers in digital form
$mat = array(array( 0, 1, 0, 1, 0 ),
array( 1, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ),
array( 0, 0, 0, 0, 1 ),
array( 0, 1, 0, 1, 0 ));
printnum($mat);
}
// Function to check number
function checkDigit($num)
{
// for digit 0
if ($num == 0)
digit0();
// for digit 1
else if ($num == 1)
digit1();
// for digit 2
else if ($num == 2)
digit2();
// for digit 3
else if ($num == 3)
digit3();
// for digit 4
else if ($num == 4)
digit4();
// for digit 5
else if ($num == 5)
digit5();
// for digit 6
else if ($num == 6)
digit6();
// for digit 7
else if ($num == 7)
digit7();
// for digit 8
else if ($num == 8)
digit8();
// for digit 9
1822
Chapter 261. Program to print numbers in digital form
else if ($num == 9)
digit9();
}
// Driver code
$num = 9;
checkDigit($num);
// This code is contributed by Mithun Kumar
?>
Output:
- -
| |
- -
|
- -
Source
https://www.geeksforgeeks.org/print-numbers-digital-form/
1823
Chapter 262
Program to swap upper diagonal elements with lower diagonal elements of matrix. - Geeks-
forGeeks
Given a square matrix, swap upper diagonal elements of matrix with lower diagonal elements
of matrix.
Examples :
Input: 2 3 5 6
4 5 7 9
8 6 4 9
1 3 5 6
Output: 2 4 8 1
3 5 6 3
5 7 4 5
6 9 9 6
Input: 1 2 3
4 5 6
7 8 9
Output: 1 4 7
2 5 8
3 6 9
1824
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.
C++
1825
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.
Java
1826
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.
}
}
// This code is contributed by vt_m.
C#
1827
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.
{ 1, 3, 5, 6 }};
// Function call
swapUpperToLower(arr);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP Program to implement matrix
// for swapping the upper diagonal
// elements with lower diagonal
// elements of matrix.
$n = 4;
// Function to swap the diagonal
// elements in a matrix.
function swapUpperToLower($arr)
{
global $n;
// Loop for swap the elements of matrix.
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1; $j < $n; $j++)
{
$temp = $arr[$i][$j];
$arr[$i][$j] = $arr[$j][$i];
$arr[$j][$i] = $temp;
}
}
// Loop for print the matrix elements.
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
echo($arr[$i][$j] . " ");
echo("\n");
}
}
// Driver Code
$arr = array(array(2, 3, 5, 6),
array(4, 5, 7, 9),
1828
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.
array(8, 6, 4, 9),
array(1, 3, 5, 6));
// Function call
swapUpperToLower($arr);
// This code is contributed by Ajit.
?>
Output :
2 4 8 1
3 5 6 3
5 7 4 5
6 9 9 6
Source
https://www.geeksforgeeks.org/program-swap-upper-diagonal-elements-lower-diagonal-elements-matrix/
1829
Chapter 263
Output : (1, 1, 0, 1, 0, 1)
(0, 0, 1, 0, 0, 1)
We have existing solution for this problem please refer Find duplicate rows in a binary
matrix link. We can solve this problem very quickly in Python using Counter() method.
Approach is very simple,
1. Create a dictionary using counter method which will have rows as key and it’s fre-
quency as value.
2. Now traverse dictionary completely and print all rows which have frequency greater
than 1.
1830
Chapter 263. Python Counter| Find duplicate rows in a binary matrix
def duplicate(input):
# since lists are unhasable for counter method
# because lists are mutable so first we will cast
# each row (list) into tuple
input = map(tuple,input)
# now create dictionary
freqDict = Counter(input)
# print all rows having frequency greater than 1
for (row,freq) in freqDict.items():
if freq>1:
print (row)
# Driver program
if __name__ == "__main__":
input = [[1, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1],
[1, 0, 1, 1, 0, 0],
[1, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 0, 1],
[0, 0, 1, 0, 0, 1]]
duplicate(input)
Output:
(1, 1, 0, 1, 0, 1)
(0, 0, 1, 0, 0, 1)
Source
https://www.geeksforgeeks.org/python-counter-find-duplicate-rows-binary-matrix/
1831
Chapter 264
Python List Equality | Program to check if two given matrices are identical - GeeksforGeeks
We are given two square matrices of same order. Check if two given matrices are identical.
Examples:
B = [ [1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
We have existing solution for this problem please refer C Program to check if two given
matrices are identical link. In python any iterable object is comparable so we can solve this
problem quickly in python with the help of List Equality.
1832
Chapter 264. Python List Equality | Program to check if two given matrices are identical
if A==B:
print ('Matrices are identical')
else:
print ('Matrices are not identical')
# Driver program
if __name__ == "__main__":
A = [ [1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
B = [ [1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
identicalMatrices(A,B)
Output:
Source
https://www.geeksforgeeks.org/python-list-equality-program-check-two-given-matrices-identical/
1833
Chapter 265
We will use similar approach like K’th Smallest/Largest Element in Unsorted Array to solve
this problem.
1834
Chapter 265. Python heapq to find K’th smallest element in a 2D array
Output:
Source
https://www.geeksforgeeks.org/python-heapq-find-kth-smallest-element-2d-array/
1835
Chapter 266
Python map function to find row with maximum number of 1’s - GeeksforGeeks
Given a boolean 2D array, where each row is sorted. Find the row with the maximum
number of 1s.
Examples:
Example
Input: matrix =
[[0, 1, 1, 1],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]]
Output: 2
We have existing solution for this problem please refer Find the row with maximum number
of 1’s. We can solve this problem in python quickly using map() function. Approach is
very simple, find sum of all 1’s in each row and then print index of maximum sum in a list
because row having maximum 1 will also have maximum sum.
1836
Chapter 266. Python map function to find row with maximum number of 1’s
Complexity : O(M*N)
Output:
Source
https://www.geeksforgeeks.org/python-map-function-find-row-maximum-number-1s/
1837
Chapter 267
Input :
X= [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
Output :
result= [[10,10,10],
[10,10,10],
[10,10,10]]
1838
Chapter 267. Python program to add two Matrices
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
Output:
Explanation :-
In this program we have used nested for loops to iterate through each row and each
column. At each point we add the corresponding elements in the two matrices and
store it in the result.
2. Using nested list comprehension : In Python, we can implement a matrix as
nested list (list inside a list). We can treat each element as a row of the matrix.
1839
Chapter 267. Python program to add two Matrices
Output:
Explanation :-
The output of this program is the same as above. We have used nested list compre-
hension to iterate through each element in the matrix. List comprehension allows us
to write concise codes and we must try to use them frequently in Python. They are
very helpful.
3. Using zip() and sum
Output:
Explanation :-
The zip function accepts iterator i of each element(list) of matrix, mapping them,
adding them using sum() and storing them in the map form.
Improved By : manjeet_04
Source
https://www.geeksforgeeks.org/python-program-add-two-matrices/
1840
Chapter 268
1841
Chapter 268. Python program to multiply two matrices
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
result = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
Output:
1842
Chapter 268. Python program to multiply two matrices
for r in result:
print(r)
Output:
Source
https://www.geeksforgeeks.org/python-program-multiply-two-matrices/
1843
Chapter 269
Python | Print unique rows in a given boolean matrix using Set with tuples - GeeksforGeeks
Given a binary matrix, print all unique rows of the given matrix. Order of row printing
doesn’t matter.
Examples:
Input:
mat = [[0, 1, 0, 0, 1],
[1, 0, 1, 1, 0],
[0, 1, 0, 0, 1],
[1, 1, 1, 0, 0]]
Output:
(1, 1, 1, 0, 0)
(0, 1, 0, 0, 1)
(1, 0, 1, 1, 0)
We have existing solution for this problem please refer link. We can solve this problem in
python quickly using Set data structure. Approach is very simple.
1. We are given list of boolean values list, put all rows (list) in set because set contains
unique values.
2. Since list is an unhashable type for set because it is mutable that’s why first we convert
each row (list) into tuple then we put all tuple in set.
3. Resultant set will contain only unique valued tuples (row).
1844
Chapter 269. Python | Print unique rows in a given boolean matrix using Set with tuples
Output:
(1, 1, 1, 0, 0)
(0, 1, 0, 0, 1)
(1, 0, 1, 1, 0)
Source
https://www.geeksforgeeks.org/python-print-unique-rows-given-boolean-matrix-using-set-tuples/
1845
Chapter 270
Queries in a Matrix
1. R(x, y): swaps the x-th and y-th rows of M where x and y vary from 1 to m.
2. C(x, y): swaps the x-th and y-th columns of M where x and y vary from 1 to n.
3. P(x, y): prints the element at x-th row and y-th column where x varies from 1 to m
and y varies from 1 to n.
Note that the given matrix is stored as a typical 2D array with indexes start from 0, but
values of x and y start from 1.
Examples:
Input : m = 3, n = 3
R(1, 2)
P(1, 1)
P(2, 1)
C(1, 2)
P(1, 1)
P(2, 1)
Output: value at (1, 1) = 4
value at (2, 1) = 1
value at (1, 1) = 5
value at (2, 1) = 2
Explanation:
The matrix is {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
1846
Chapter 270. Queries in a Matrix
A simple solution for this problem is to finish all the queries manually, that means when
we have to swap the rows just swap the elements of x’th row and y’th row and similarly
for column swamping. But this approach may have time complexity of q*O(m) or q*O(n)
where ‘q’ is number of queries and auxiliary space required O(m*n).
An efficient approach for this problem requires little bit mathematical observation. Here
we are given that elements in matrix are filled from 1 to mxn sequentially in row major
order, so we will take advantage of this given scenario and can solve this problem.
• Create an auxiliary array rows[m] and fill it with values 0 to m-1 sequentially.
• Create another auxiliary array cols[n] and fill it with values 0 to n-1 sequentially.
• Now for query ‘R(x, y)’ just swap the value of rows[x-1] with rows[y-1].
• Now for query ‘C(x, y)’ just swap the value of cols[x-1] with cols[y-1].
• Now for query ‘P(x, y)’ just skip the number of columns you have seen and calculate
the value at (x, y) by rows[x-1]*n + cols[y-1] + 1.
1847
Chapter 270. Queries in a Matrix
1848
Chapter 270. Queries in a Matrix
// row[] is array for rows and cols[]
// is array for coloumns
int rows[m], cols[n];
// Fill initial values in rows[] and cols[]
preprocessMatrix(rows, cols, m, n);
queryMatrix(rows, cols, m, n, 'R', 1, 2);
queryMatrix(rows, cols, m, n, 'P', 1, 1);
queryMatrix(rows, cols, m, n, 'P', 2, 1);
queryMatrix(rows, cols, m, n, 'C', 1, 2);
queryMatrix(rows, cols, m, n, 'P', 1, 1);
queryMatrix(rows, cols, m, n, 'P', 2, 1);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/queries-in-a-matrix/
1849
Chapter 271
Query(a, b): Find the number of sub matrices of size a X a with each of its
element consisting of the Binary Number b.
We basically need to find submatrices of given sizes with all 1s or all 0s.
Examples:
Input : N = 5, M = 4
m[][] = { { 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 }
}
Q = 2
Query 1 : a = 2, b = 1
Query 2 : a = 2, b = 0
Output : 4 1
Explanation:
For Query 1,
0011 0011 0011 0011
0010 0010 0010 0010
0111 0111 0111 0111
1850
Chapter 271. Queries on number of Binary sub-matrices of Given size
For Query 2,
0011
0010
0111
1111
0111
Input : N = 5, M = 4
m[][] = { { 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 }
}
Q = 1
Query 1 : a = 3, b = 1
Output : 1
The idea is to use Dynamic Programming to solve the problem. First declare a 2D array
dp[][], where value at dp[i][j] (say K) indicates the size of the largest square sub-matrix (K
X K) that can be formed whose all elements are equal to m[i][j] and (i, j) is the last element
(south-east) of the sub matrix. Now, dp[i][j] can be defined as:
Now, traverse the 2D dp[][] array and calculate the frequency (freq0[] for the element 0,
freq1[] for the element 1) of all the distinct values i.e distinct sizes of square sub-matrix for
both 0s and 1s.
Observe, that to count the square sub-matrix of size Y X Y, then Y+1 X Y+1 will also
contribute 1 count. Suppose we need to count 2 X 2 matrix and dp[][]=
1851
Chapter 271. Queries on number of Binary sub-matrices of Given size
...22
...23
Here, the frequency of two is 3 but observe element where dp[i][j] = 3 is also contributing a
2 X 2 square sub-matrix.
So, find the cumulative sum of the frequency for both freq0[] and freq1[].
Below is the implementation of this approach:
C++
1852
Chapter 271. Queries on number of Binary sub-matrices of Given size
+ 1;
if (max < dp[i][j])
max = dp[i][j];
}
else
dp[i][j] = 1;
}
}
int freq0[MAX] = { 0 }, freq1[MAX] = { 0 };
// Find frequency of each distinct size
// for 0s and 1s.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0)
freq0[dp[i][j]]++;
else
freq1[dp[i][j]]++;
}
}
// Find the Cumulative Sum.
for (int i = max - 1; i >= 0; i--) {
freq0[i] += freq0[i + 1];
freq1[i] += freq1[i + 1];
}
// Output the answer for each query
for (int i = 0; i < q; i++) {
if (binary[i] == 0)
cout << freq0[a[i]] << endl;
else
cout << freq1[a[i]] << endl;
}
}
// Driver Program
int main()
{
int n = 5, m = 4;
int mat[N][M] = {
{ 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
1853
Chapter 271. Queries on number of Binary sub-matrices of Given size
{ 0, 1, 1, 1 }
};
int q = 2;
int a[] = { 2, 2 };
int binary[] = { 1, 0 };
solveQuery(n, m, mat, q, a, binary);
return 0;
}
Java
1854
Chapter 271. Queries on number of Binary sub-matrices of Given size
1855
Chapter 271. Queries on number of Binary sub-matrices of Given size
{
int n = 5, m = 4;
int mat[][] = { { 0, 0, 1, 1 },
{ 0, 0, 1, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 } };
int q = 2;
int a[] = { 2, 2 };
int binary[] = { 1, 0 };
solveQuery(n, m, mat, q, a, binary);
}
}
// This code is contributed by anuj_67.
C#
// C# Program to answer
// queries on number of
// submatrix of given size
using System;
class GFG
{
static int MAX = 100;
// static int N = 5;
// static int M = 4;
// Return the minimum
// of three numbers
static int min(int a,
int b,
int c)
{
return Math.Min(a, Math.Min(b, c));
}
// Solve each query on matrix
static void solveQuery(int n, int m,
int [,]mat, int q,
int []a, int []binary)
{
int [,]dp = new int[n, m];
int max = 1;
// For each of the cell.
1856
Chapter 271. Queries on number of Binary sub-matrices of Given size
1857
Chapter 271. Queries on number of Binary sub-matrices of Given size
Output:
4
1
Source
https://www.geeksforgeeks.org/queries-number-binary-sub-matrices-given-size/
1858
Chapter 272
Explanation
Rat started with M[0][0] and can jump upto 2 steps right/down.
1859
Chapter 272. Rat in a Maze with multiple steps or jump allowed
Input : {
{2, 1, 0, 0},
{2, 0, 0, 1},
{0, 1, 0, 1},
{0, 0, 0, 1}
}
Output : Solution doesn't exist
Naive Algorithm
The Naive Algorithm is to generate all paths from source to destination and one by one
check if the generated path satisfies the constraints.
Backtracking Algorithm
If destination is reached
print the solution matrix
Else
a) Mark current cell in solution matrix as 1.
b) Move forward/jump (for each valid steps) in horizontal direction
and recursively check if this move leads to a solution.
c) If the move chosen in the above step doesn't lead to a solution
then move down and check if this move leads to a solution.
d) If none of the above solutions work then unmark this cell as 0
(BACKTRACK) and return false.
1860
Chapter 272. Rat in a Maze with multiple steps or jump allowed
// Maze size
#define N 4
bool solveMazeUtil(int maze[N][N], int x, int y,
int sol[N][N]);
/* A utility function to print solution matrix
sol[N][N] */
void printSolution(int sol[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(" %d ", sol[i][j]);
printf("\n");
}
}
/* A utility function to check if x, y is valid
index for N*N maze */
bool isSafe(int maze[N][N], int x, int y)
{
// if (x, y outside maze) return false
if (x >= 0 && x < N && y >= 0 &&
y < N && maze[x][y] != 0)
return true;
return false;
}
/* This function solves the Maze problem using
Backtracking. It mainly uses solveMazeUtil() to
solve the problem. It returns false if no path
is possible, otherwise return true and prints
the path in the form of 1s. Please note that
there may be more than one solutions,
this function prints one of the feasible solutions.*/
bool solveMaze(int maze[N][N])
{
int sol[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveMazeUtil(maze, 0, 0, sol) == false) {
printf("Solution doesn't exist");
return false;
}
1861
Chapter 272. Rat in a Maze with multiple steps or jump allowed
printSolution(sol);
return true;
}
/* A recursive utility function to solve Maze problem */
bool solveMazeUtil(int maze[N][N], int x, int y,
int sol[N][N])
{
// if (x, y is goal) return true
if (x == N - 1 && y == N - 1) {
sol[x][y] = 1;
return true;
}
// Check if maze[x][y] is valid
if (isSafe(maze, x, y) == true) {
// mark x, y as part of solution path
sol[x][y] = 1;
/* Move forward in x direction */
for (int i = 1; i <= maze[x][y] && i < N; i++) {
/* Move forward in x direction */
if (solveMazeUtil(maze, x + i, y, sol) == true)
return true;
/* If moving in x direction doesn't give
solution then Move down in y direction */
if (solveMazeUtil(maze, x, y + i, sol) == true)
return true;
}
/* If none of the above movements work then
BACKTRACK: unmark x, y as part of solution
path */
sol[x][y] = 0;
return false;
}
return false;
}
// driver program to test above function
int main()
{
int maze[N][N] = { { 2, 1, 0, 0 },
{ 3, 0, 0, 1 },
1862
Chapter 272. Rat in a Maze with multiple steps or jump allowed
{ 0, 1, 0, 1 },
{ 0, 0, 0, 1 } };
solveMaze(maze);
return 0;
}
Output:
1 0 0 0
1 0 0 1
0 0 0 1
0 0 0 1
Source
https://www.geeksforgeeks.org/rat-in-a-maze-with-multiple-steps-jump-allowed/
1863
Chapter 273
{1, 0, 0, 0}
1864
Chapter 273. Rat in a Maze | Backtracking-2
{1, 1, 0, 1}
{0, 1, 0, 0}
{1, 1, 1, 1}
Following is the solution matrix (output of program) for the above input matrx.
{1, 0, 0, 0}
{1, 1, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 1}
All enteries in solution path are marked as 1.
Naive Algorithm
The Naive Algorithm is to generate all paths from source to destination and one by one
check if the generated path satisfies the constraints.
Backtracking Algorithm
If destination is reached
print the solution matrix
Else
a) Mark current cell in solution matrix as 1.
b) Move forward in the horizontal direction and recursively check if this
move leads to a solution.
1865
Chapter 273. Rat in a Maze | Backtracking-2
C/C++
1866
Chapter 273. Rat in a Maze | Backtracking-2
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
if(solveMazeUtil(maze, 0, 0, sol) == false)
{
printf("Solution doesn't exist");
return false;
}
printSolution(sol);
return true;
}
/* A recursive utility function to solve Maze problem */
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])
{
// if (x,y is goal) return true
if(x == N-1 && y == N-1)
{
sol[x][y] = 1;
return true;
}
// Check if maze[x][y] is valid
if(isSafe(maze, x, y) == true)
{
// mark x,y as part of solution path
sol[x][y] = 1;
/* Move forward in x direction */
if (solveMazeUtil(maze, x+1, y, sol) == true)
return true;
/* If moving in x direction doesn't give solution then
Move down in y direction */
if (solveMazeUtil(maze, x, y+1, sol) == true)
return true;
/* If none of the above movements work then BACKTRACK:
unmark x,y as part of solution path */
sol[x][y] = 0;
return false;
}
return false;
}
1867
Chapter 273. Rat in a Maze | Backtracking-2
// driver program to test above function
int main()
{
int maze[N][N] = { {1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1}
};
solveMaze(maze);
return 0;
}
Java
1868
Chapter 273. Rat in a Maze | Backtracking-2
1869
Chapter 273. Rat in a Maze | Backtracking-2
/* If none of the above movements works then
BACKTRACK: unmark x,y as part of solution
path */
sol[x][y] = 0;
return false;
}
return false;
}
public static void main(String args[])
{
RatMaze rat = new RatMaze();
int maze[][] = {{1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1}
};
rat.solveMaze(maze);
}
}
// This code is contributed by Abhishek Shankhadhar
Python3
1870
Chapter 273. Rat in a Maze | Backtracking-2
""" This function solves the Maze problem using Backtracking.
It mainly uses solveMazeUtil() to solve the problem. It
returns false if no path is possible, otherwise return
true and prints the path in the form of 1s. Please note
that there may be more than one solutions, this function
prints one of the feasable solutions. """
def solveMaze( maze ):
# Creating a 4 * 4 2-D list
sol = [ [ 0 for j in range(4) ] for i in range(4) ]
if solveMazeUtil(maze, 0, 0, sol) == False:
print("Solution doesn't exist");
return False
printSolution(sol)
return True
# A recursive utility function to solve Maze problem
def solveMazeUtil(maze, x, y, sol):
#if (x,y is goal) return True
if x == N - 1 and y == N - 1:
sol[x][y] = 1
return True
# Check if maze[x][y] is valid
if isSafe(maze, x, y) == True:
# mark x, y as part of solution path
sol[x][y] = 1
# Move forward in x direction
if solveMazeUtil(maze, x + 1, y, sol) == True:
return True
# If moving in x direction doesn't give solution
# then Move down in y direction
if solveMazeUtil(maze, x, y + 1, sol) == True:
return True
# If none of the above movements work then
# BACKTRACK: unmark x,y as part of solution path
sol[x][y] = 0
return False
# Driver program to test above function
if __name__ == "__main__":
1871
Chapter 273. Rat in a Maze | Backtracking-2
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
Source
https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/
1872
Chapter 274
Remove all outgoing edges except edge with minimum weight - GeeksforGeeks
Given a directed graph having n nodes. For each node, delete all the outgoing edges except
the outgoing edge with minimum weight. Apply this deletion operation for every node and
then print the final graph remained where each node of the graph has at most one outgoing
edge and that too with minimum weight.
Note: Here, graph is stored as Adjacency Matrix for ease.
Examples :
1873
Chapter 274. Remove all outgoing edges except edge with minimum weight
For every row of the adjacency matrix of graph keep the minimum element (except zero)
and make rest of all zero. Do this for every row of the input matrix. Finally, print the
resultant Matrix.
Example :
C++
1874
Chapter 274. Remove all outgoing edges except edge with minimum weight
1875
Chapter 274. Remove all outgoing edges except edge with minimum weight
Java
1876
Chapter 274. Remove all outgoing edges except edge with minimum weight
{
int min;
// Set empty edges
// to INT_MAX
for (int i = 0;
i < arr.length; i++)
for (int j = 0;
j < arr.length; j++)
if (arr[i][j] == 0)
arr[i][j] = Integer.MAX_VALUE;
// Finding minimum of each
// row and deleting rest
// of edges
for (int i = 0;
i < arr.length; i++)
{
// Find minimum
// element of row
min = minFn(arr[i]);
for (int j = 0;
j < arr.length; j++)
{
// If edge value is not
// min set it to zero,
// also edge value INT_MAX
// denotes that initially
// edge value was zero
if ((arr[i][j] != min) ||
(arr[i][j] == Integer.MAX_VALUE))
arr[i][j] = 0;
else
min = 0;
}
}
// Print result;
for (int i = 0;
i < arr.length; i++)
{
for (int j = 0;
j < arr.length; j++)
System.out.print(arr[i][j] + " ");
System.out.print("\n");
}
1877
Chapter 274. Remove all outgoing edges except edge with minimum weight
}
// Driver Code
public static void main(String[] args)
{
// Input Graph
int arr[][] = {{1, 2, 4, 0},
{0, 0, 0, 5},
{0, 2, 0, 3},
{0, 0, 0, 0}};
minimizeGraph(arr);
}
}
Output:
1 0 0 0
0 0 0 5
0 2 0 0
0 0 0 0
Source
https://www.geeksforgeeks.org/minimum-weighted-graph/
1878
Chapter 275
Input : zx
xz
Output :zxxz
Approach : Traverse the entire matrix and for every element, check its corresponding row
and column. If there are duplicates, then mark that particular cell in another matrix as
1879
Chapter 275. Removing row or column wise duplicates from matrix of characters
true. Finally, all the characters for which there is false value in another matrix are joined
to form the string.
C++
1880
Chapter 275. Removing row or column wise duplicates from matrix of characters
if (!isPresent[i][j])
printf("%c", a[i][j]);
}
// Driver code
int main()
{
int n = 2, m = 5;
// character array
string a[] = { "zx", "xz" };
// Calling function
findDuplciates(a, n, m);
return 0;
}
C#
1881
Chapter 275. Removing row or column wise duplicates from matrix of characters
{
if (a[i][j] == a[k][j] &&
i != k)
{
isPresent[i, j] = true;
isPresent[k, j] = true;
}
}
// Checking every column for
// duplicate characters
for (int k = 0; k < m; k++)
{
if (a[i][j] == a[i][k] &&
j != k)
{
isPresent[i, j] = true;
isPresent[i, k] = true;
}
}
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
// If the character is
// unique in its row
// and column
if (!isPresent[i, j])
Console.Write(a[i][j]);
}
// Driver code
static void Main()
{
int n = 2, m = 2;
// character array
string []a = new string[]{"zx",
"xz"};
// Calling function
findDuplciates(a, n, m);
}
}
// This code is contributed by
1882
Chapter 275. Removing row or column wise duplicates from matrix of characters
// Manish Shaw(manishshaw1)
Output:
zxxz
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/removing-row-column-wise-duplicates-matrix-characters/
1883
Chapter 276
Replace every matrix element with maximum of GCD of row or column - GeeksforGeeks
Given a matrix of n rows and m columns. The task is to replace each matrix element with
Greatest Common Divisor of its row or column, whichever is maximum. That is, for each
element (i, j) replace it from GCD of i’th row or GCD of j’th row, whichever is greater.
Examples :
The idea is to us concept discussed here LCM of an array to find the GCD of row and
column.
Using the brute force, we can traverse element of matrix, find the GCD of row and column
corresponding to the element and replace it with maximum of both.
An Efficient method is to make two arrays of size n and m for row and column respectively.
And store the GCD of each row and each column. An Array of size n will contain GCD
of each row and array of size m will contain the GCD of each column. And replace each
element with maximum of its corresponding row GCD or column GCD.
1884
Chapter 276. Replace every matrix element with maximum of GCD of row or column
C++
1885
Chapter 276. Replace every matrix element with maximum of GCD of row or column
1, 2, 3, 3,
4, 5, 6, 6,
7, 8, 9, 9,
};
replacematrix(m, R, C);
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
cout << m[i][j] << " ";
cout<<endl;
}
return 0;
}
Java
1886
Chapter 276. Replace every matrix element with maximum of GCD of row or column
{
for (int j = 0; j < m; j++)
{
rgcd[i] = gcd(rgcd[i], mat[i][j]);
cgcd[j] = gcd(cgcd[j], mat[i][j]);
}
}
// Replacing matrix element
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat[i][j] = Math.max(rgcd[i], cgcd[j]);
}
// Driver program
static public void main (String[] args){
int [][]m =
{
{1, 2, 3, 3},
{4, 5, 6, 6},
{7, 8, 9, 9},
};
replacematrix(m, R, C);
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
//This code is contributed by vt_m.
C#
1887
Chapter 276. Replace every matrix element with maximum of GCD of row or column
1888
Chapter 276. Replace every matrix element with maximum of GCD of row or column
Console.WriteLine();
}
}
}
//This code is contributed by vt_m.
Output:
1 1 3 3
1 1 3 3
1 1 3 3
Source
https://www.geeksforgeeks.org/replace-matrix-element-maximum-gcd-row-column/
1889
Chapter 277
1890
Chapter 277. Return previous element in an expanding matrix
[ac ad bc bd] [ac ad bc bd] [cca ccb cda cdb dca dcb dda ddb]
[ca cb da db] [ca cb da db] [ccc ccd cdc cdd dcc dcd ddc ddd]
[cc cd dc dd] [cc cd dc dd]
Basically for a given sequence, we need to find out the sequence just left to it. The matrix
may be assumed circular i.e. sequence present at postion (i, 0) should return sequence
present at position (i, N-1)
Examples:
We strongly recommend you to minimize your browser and try this yourself
first.
If we carefully analyze, we can see a pattern here.
Algorithm:
We start scanning the string from rightmost position and for each character do the following
–
1. If the current character is ‘b’ or ‘d’, change to ‘a’ or ‘c’ respectively and return the string.
2. If the current character is ‘a’ or ‘c’, change it to ‘b’ or ‘d’ respectively and move to the
next character to the left. Repeat Step 1 for the next left character.
C++
1891
Chapter 277. Return previous element in an expanding matrix
Java
1892
Chapter 277. Return previous element in an expanding matrix
Output :
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
1893
Chapter 277. Return previous element in an expanding matrix
Source
https://www.geeksforgeeks.org/return-previous-element-in-an-expanding-matrix/
1894
Chapter 278
Input : {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output :{9, 2, 7,
4, 5, 6,
3, 8, 1}
Explanation:
Major Diagonal Elements before: 1 5 9
After reverse: 9 5 1
Minor Diagonal Elements before: 3 5 7
After reverse: 7 5 3
Input :{1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16}
C++
1895
Chapter 278. Reverse Diagonal elements of matrix
#include <bits/stdc++.h>
using namespace std;
#define N 4
// Function to swap diagonals elements
void reverseDiagonal(int array[][N])
{
int i = 0, j = N;
while (i < j) {
// For reversing elements of major
// diagonal.
swap(array[i][i], array[j - 1][j - 1]);
// For reversing elements of minor
// diagonal.
swap(array[i][j - 1], array[j - 1][i]);
i++;
j--;
}
// Print matrix after reversals.
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j)
printf("%d ", array[i][j]);
printf("\n");
}
}
// Driver function
int main()
{
int matrix[N][N] = { 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16 };
reverseDiagonal(matrix);
return 0;
}
Java
1896
Chapter 278. Reverse Diagonal elements of matrix
class GFG
{
static int N = 4;
// Function to swap
// diagonals elements
static void reverseDiagonal(int array[][])
{
int i = 0, j = N;
int temp = 0;
while (i < j)
{
// For reversing elements
// of major diagonal.
temp = array[i][i];
array[i][i] = array[j - 1][j - 1];
array[j - 1][j - 1] = temp;
// For reversing elements
// of minor diagonal.
temp = array[i][j - 1];
array[i][j - 1] = array[j - 1][i];
array[j - 1][i] = temp;
i++;
j--;
}
// Print matrix after
// reversals.
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
System.out.print(array[i][j] + " ");
System.out.println();
}
}
// Driver Code
public static void main (String[] args)
{
int matrix[][] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
1897
Chapter 278. Reverse Diagonal elements of matrix
reverseDiagonal(matrix);
}
}
// This code is contributed
// by anuj_67.
C#
// C# Program to Reverse
// Diagonal elements of matrix
using System;
class GFG
{
static int N = 4;
// Function to swap
// diagonals elements
static void reverseDiagonal(int [,]array)
{
int i = 0, j = N;
int temp = 0;
while (i < j)
{
// For reversing elements
// of major diagonal.
temp = array[i, i];
array[i, i] = array[j - 1, j - 1];
array[j - 1, j - 1] = temp;
// For reversing elements
// of minor diagonal.
temp = array[i, j - 1];
array[i, j - 1] = array[j - 1, i];
array[j - 1, i] = temp;
i++;
j--;
}
// Print matrix after
// reversals.
for (i = 0; i < N; ++i)
{
1898
Chapter 278. Reverse Diagonal elements of matrix
Output:
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Improved By : vt_m
Source
https://www.geeksforgeeks.org/reverse-diagonal-elements-matrix/
1899
Chapter 279
Input
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
The idea is to use loops similar to the program for printing a matrix in spiral form. One by
one rotate all rings of elements, starting from the outermost. To rotate a ring, we need to
1900
Chapter 279. Rotate Matrix Elements
do following.
1) Move elements of top row.
2) Move elements of last column.
3) Move elements of bottom row.
4) Move elements of first column.
Repeat above steps for inner ring while there is an inner ring.
Below is the implementation of above idea. Thanks to Gaurav Ahirwar for suggesting
below solution.
C/C++
1901
Chapter 279. Rotate Matrix Elements
mat[row][i] = prev;
prev = curr;
}
row++;
/* Move elements of last column from the remaining columns */
for (int i = row; i < m; i++)
{
curr = mat[i][n-1];
mat[i][n-1] = prev;
prev = curr;
}
n--;
/* Move elements of last row from the remaining rows */
if (row < m)
{
for (int i = n-1; i >= col; i--)
{
curr = mat[m-1][i];
mat[m-1][i] = prev;
prev = curr;
}
}
m--;
/* Move elements of first column from the remaining rows */
if (col < n)
{
for (int i = m-1; i >= row; i--)
{
curr = mat[i][col];
mat[i][col] = prev;
prev = curr;
}
}
col++;
}
// Print rotated matrix
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
1902
Chapter 279. Rotate Matrix Elements
Java
1903
Chapter 279. Rotate Matrix Elements
1904
Chapter 279. Rotate Matrix Elements
mat[i][col] = prev;
prev = curr;
}
}
col++;
}
// Print rotated matrix
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
System.out.print( mat[i][j] + " ");
System.out.print("\n");
}
}
/* Driver program to test above functions */
public static void main(String[] args)
{
// Test Case 1
int a[][] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
// Tese Case 2
/* int a[][] = new int {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};*/
rotatematrix(R, C, a);
}
}
// This code is contributed by Sahil_Bansall
Python
1905
Chapter 279. Rotate Matrix Elements
1906
Chapter 279. Rotate Matrix Elements
left += 1
return mat
# Utility Function
def printMatrix(mat):
for row in mat:
print row
# Test case 1
matrix =[
[1, 2, 3, 4 ],
[5, 6, 7, 8 ],
[9, 10, 11, 12 ],
[13, 14, 15, 16 ]
]
# Test case 2
"""
matrix =[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
"""
matrix = rotateMatrix(matrix)
# Print modified matrix
printMatrix(matrix)
C#
1907
Chapter 279. Rotate Matrix Elements
1908
Chapter 279. Rotate Matrix Elements
prev = curr;
}
}
m--;
// Move elements of first column
// from the remaining rows
if (col < n)
{
for (int i = m-1; i >= row; i--)
{
curr = mat[i,col];
mat[i,col] = prev;
prev = curr;
}
}
col++;
}
// Print rotated matrix
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
Console.Write( mat[i,j] + " ");
Console.Write("\n");
}
}
/* Driver program to test above functions */
public static void Main()
{
// Test Case 1
int [,]a = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
// Tese Case 2
/* int a[][] = new int {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};*/
rotatematrix(R, C, a);
}
}
// This code is contributed by nitin mittal.
1909
Chapter 279. Rotate Matrix Elements
PHP
<?php
// PHP program to rotate a matrix
$R = 4;
$C = 4;
// A function to rotate a matrix
// mat[][] of size R x C. Initially,
// m = R and n = C
function rotatematrix($m, $n, $mat)
{
global $R, $C;
$row = 0;
$col = 0;
$prev = 0;
$curr = 0;
/*
row - Staring row index
m - ending row index
col - starting column index
n - ending column index
i - iterator
*/
while ($row < $m && $col < $n)
{
if ($row + 1 == $m ||
$col + 1 == $n)
break;
// Store the first element
// of next row, this element
// will replace first element
// of current row
$prev = $mat[$row + 1][$col];
/* Move elements of first row
from the remaining rows */
for ($i = $col; $i < $n; $i++)
{
$curr = $mat[$row][$i];
$mat[$row][$i] = $prev;
$prev = $curr;
}
$row++;
1910
Chapter 279. Rotate Matrix Elements
1911
Chapter 279. Rotate Matrix Elements
// Driver code
// Test Case 1
$a = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 10, 11, 12),
array(13, 14, 15, 16));
// Tese Case 2
/* int $a = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
*/ rotatematrix($R, $C, $a);
return 0;
// This code is contributed
// by ChitraNayal
?>
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Source
https://www.geeksforgeeks.org/rotate-matrix-elements/
1912
Chapter 280
Input : 1 2 3
4 5 6
7 8 9
Output : 9 8 7
6 5 4
3 2 1
Input : 1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6
Output : 6 5 4 3
2 1 0 9
8 7 6 5
4 3 2 1
1913
Chapter 280. Rotate a Matrix by 180 degree
From the above illustration we get that simply to rotate the matrix by 180
degree then we will have to print given matrix in reverse manner .
C++
Java
1914
Chapter 280. Rotate a Matrix by 180 degree
Python3
1915
Chapter 280. Rotate a Matrix by 180 degree
i = N - 1;
while(i >= 0):
j = N - 1;
while(j >= 0):
print(mat[i][j], end = " ");
j = j - 1;
print();
i = i - 1;
# Driven code
mat = [[1, 2, 3],
[ 4, 5, 6 ],
[ 7, 8, 9 ]];
rotateMatrix(mat);
# This code is contributed
# by mits
C#
// C# program to rotate a
// matrix by 180 degrees
using System;
class GFG {
static int N = 3;
// Function to Rotate the
// matrix by 180 degree
static void rotateMatrix(int[, ] mat)
{
// Simply print from last
// cell to first cell.
for (int i = N - 1; i >= 0; i--) {
for (int j = N - 1; j >= 0; j--)
Console.Write(mat[i, j] + " ");
Console.WriteLine();
}
}
// Driver Code
static public void Main()
{
int[, ] mat = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
1916
Chapter 280. Rotate a Matrix by 180 degree
rotateMatrix(mat);
}
}
// This code is contributed by aj_36
PHP
<?php
// PHP program to rotate
// a matrix by 180 degree
$N = 3;
// Function to Rotate the
// matrix by 180 degree
function rotateMatrix($mat)
{
global $N;
// Simply print from
// last cell to first cell.
for ($i = $N - 1; $i >= 0; $i--)
{
for ($j = $N - 1; $j >= 0; $j--)
echo $mat[$i][$j], " ";
echo "\n";
}
}
// Driver Code
$mat = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
rotateMatrix($mat);
// This code is contributed by ajit
?>
Output :
9 8 7
6 5 4
3 2 1
1917
Chapter 280. Rotate a Matrix by 180 degree
C++
1918
Chapter 280. Rotate a Matrix by 180 degree
#define R 4
#define C 4
// Function to rotate the matrix by 180 degree
void reverseColumns(int arr[R][C])
{
for (int i = 0; i < C; i++)
for (int j = 0, k = C - 1; j < k; j++, k--)
swap(arr[j][i], arr[k][i]);
}
// Function for transpose of matrix
void transpose(int arr[R][C])
{
for (int i = 0; i < R; i++)
for (int j = i; j < C; j++)
swap(arr[i][j], arr[j][i]);
}
// Function for display the matrix
void printMatrix(int arr[R][C])
{
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++)
cout << arr[i][j] << " ";
cout << '\n';
}
}
// Function to anticlockwise rotate matrix
// by 180 degree
void rotate180(int arr[R][C])
{
transpose(arr);
reverseColumns(arr);
transpose(arr);
reverseColumns(arr);
}
// Driven code
int main()
{
int arr[R][C] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotate180(arr);
1919
Chapter 280. Rotate a Matrix by 180 degree
printMatrix(arr);
return 0;
}
Java
1920
Chapter 280. Rotate a Matrix by 180 degree
C#
1921
Chapter 280. Rotate a Matrix by 180 degree
Python 3
1922
Chapter 280. Rotate a Matrix by 180 degree
1923
Chapter 280. Rotate a Matrix by 180 degree
PHP
<?php
// PHP program for left rotation of matrix by 180
$R = 4;
$C = 4;
// Function to rotate the matrix by 180 degree
function reverseColumns(&$arr)
{
global $C;
for ($i = 0; $i < $C; $i++)
{
for ($j = 0, $k = $C - 1; $j < $k; $j++, $k--)
{
$t = $arr[$j][$i];
$arr[$j][$i] = $arr[$k][$i];
$arr[$k][$i] = $t;
}
}
}
// Function for transpose of matrix
function transpose(&$arr)
{
global $R, $C;
for ($i = 0; $i < $R; $i++)
{
for ($j = $i; $j < $C; $j++)
{
$t = $arr[$i][$j];
$arr[$i][$j] = $arr[$j][$i];
$arr[$j][$i] = $t;
}
}
}
// Function for display the matrix
function printMatrix(&$arr)
{
global $R, $C;
for ($i = 0; $i < $R; $i++) {
for ($j = 0; $j < $C; $j++)
{
echo $arr[$i][$j]." ";
}
echo "\n";
1924
Chapter 280. Rotate a Matrix by 180 degree
}
}
// Function to anticlockwise rotate matrix
// by 180 degree
function rotate180(&$arr)
{
transpose($arr);
reverseColumns($arr);
transpose($arr);
reverseColumns($arr);
}
// Driven code
$arr = array( array( 1, 2, 3, 4 ),
array( 5, 6, 7, 8 ),
array( 9, 10, 11, 12 ),
array( 13, 14, 15, 16 ) );
rotate180($arr);
printMatrix($arr);
return 0;
?>
Output :
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
Source
https://www.geeksforgeeks.org/rotate-matrix-180-degree/
1925
Chapter 281
Rotate a matrix by 90 degree in clockwise direction without using any extra space - Geeks-
forGeeks
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any
extra space.
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
7 4 1
8 5 2
9 6 3
Input:
1 2
3 4
Output:
3 1
4 2
Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1.
The only thing that is different is to print the elements of cycle in clockwise direction i.e.
1926
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space
C++
1927
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space
Java
1928
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space
// Swap elements of each cycle
// in clockwise direction
int temp = a[i][j];
a[i][j] = a[N - 1 - j][i];
a[N - 1 - j][i] = a[N - 1 - i][N - 1 - j];
a[N - 1 - i][N - 1 - j] = a[j][N - 1 - i];
a[j][N - 1 - i] = temp;
}
}
}
// Function for print matrix
static void printMatrix(int arr[][])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print( arr[i][j] + " ");
System.out.println();
}
}
// Driver code
public static void main (String[] args)
{
int arr[][] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotate90Clockwise(arr);
printMatrix(arr);
}
}
// This code has been contributed by inder_verma.
Python
1929
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space
C#
// C# implementation of above approach
using System;
class GFG
{
static int N = 4;
// Function to rotate the matrix
// 90 degree clockwise
static void rotate90Clockwise(int[,] a)
{
// Traverse each cycle
for (int i = 0; i < N / 2; i++) { for (int j = i; j < N - i - 1; j++) { // Swap elements of each
cycle // in clockwise direction int temp = a[i, j]; a[i, j] = a[N - 1 - j, i]; a[N - 1 - j, i] = a[N -
1 - i, N - 1 - j]; a[N - 1 - i, N - 1 - j] = a[j, N - 1 - i]; a[j, N - 1 - i] = temp; } } } // Function
for print matrix static void printMatrix(int[,] arr) { for (int i = 0; i < N; i++) { for (int j
= 0; j < N; j++) Console.Write( arr[i, j] + ” ”); Console.Write(”\n”); } } // Driver code
public static void Main () { int [,]arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14,
15, 16}}; rotate90Clockwise(arr); printMatrix(arr); } } // This code is contributed // by
ChitraNayal [tabby title=”PHP”]
Output:
13 9 5 1
14 10 6 2
1930
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space
15 11 7 3
16 12 8 4
Source
https://www.geeksforgeeks.org/rotate-a-matrix-by-90-degree-in-clockwise-direction-without-using-any-extra-space/
1931
Chapter 282
Rotate a matrix by 90 degree without using any extra space | Set 2 - GeeksforGeeks
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any
extra space.
Examples:
Input
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
1932
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
C++
1933
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
Java
1934
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
import java.util.*;
class GFG {
// After transpose we swap elements of
// column one by one for finding left
// rotation of matrix by 90 degree
static void reverseColumns(int arr[][])
{
for (int i = 0; i < arr[0].length; i++)
for (int j = 0, k = arr[0].length - 1;
j < k; j++, k--) {
int temp = arr[j][i];
arr[j][i] = arr[k][i];
arr[k][i] = temp;
}
}
// Function for do transpose of matrix
static void transpose(int arr[][])
{
for (int i = 0; i < arr.length; i++)
for (int j = i; j < arr[0].length; j++) {
int temp = arr[j][i];
arr[j][i] = arr[i][j];
arr[i][j] = temp;
}
}
// Function for print matrix
static void printMatrix(int arr[][])
{
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println("");
}
}
// Function to anticlockwise rotate
// matrix by 90 degree
static void rotate90(int arr[][])
{
transpose(arr);
reverseColumns(arr);
}
/* Driver program to test above function */
1935
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
C#
1936
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
Python 3
1937
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
PHP
<?php
// PHP program for left rotation of matrix by 90
1938
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
$R = 4;
$C = 4;
// Function to rotate the matrix by 90 degree
function reverseColumns(&$arr)
{
global $C;
for ($i = 0; $i < $C; $i++)
{
for ($j = 0, $k = $C - 1; $j < $k; $j++, $k--)
{
$t = $arr[$j][$i];
$arr[$j][$i] = $arr[$k][$i];
$arr[$k][$i] = $t;
}
}
}
// Function for transpose of matrix
function transpose(&$arr)
{
global $R, $C;
for ($i = 0; $i < $R; $i++)
{
for ($j = $i; $j < $C; $j++)
{
$t = $arr[$i][$j];
$arr[$i][$j] = $arr[$j][$i];
$arr[$j][$i] = $t;
}
}
}
// Function for display the matrix
function printMatrix(&$arr)
{
global $R, $C;
for ($i = 0; $i < $R; $i++) {
for ($j = 0; $j < $C; $j++)
echo $arr[$i][$j]." ";
echo "\n";
}
}
// Function to anticlockwise rotate matrix
// by 90 degree
function rotate90(&$arr)
{
1939
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
transpose($arr);
reverseColumns($arr);
}
// Driven code
$arr = array( array( 1, 2, 3, 4 ),
array( 5, 6, 7, 8 ),
array( 9, 10, 11, 12 ),
array( 13, 14, 15, 16 ) );
rotate90($arr);
printMatrix($arr);
return 0;
?>
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
1940
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2
Source
https://www.geeksforgeeks.org/rotate-matrix-90-degree-without-using-extra-space-set-2/
1941
Chapter 283
Input : k = 3
mat[4][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}}
Output: 4 8 12 16
3 10 6 15
2 11 7 14
1 5 9 13
Input : k = 2
mat[3][4] = {{1, 2, 3, 4},
{10, 11, 12, 5},
{9, 8, 7, 6}}
Output: 3 4 5 6
2 11 12 7
1 10 9 8
The idea is to traverse matrix in spiral form. Here is the algorithm to solve this problem :
1942
Chapter 283. Rotate each ring of matrix anticlockwise by K elements
• Start traversing matrix in spiral form and store elements of current ring in temp[]
array. While storing the elements in temp, keep track of starting and ending positions
of current ring.
• For every ring that is being stored in temp[], rotate that subarray temp[]
• Repeat this process for each ring of matrix.
• In last traverse matrix again spirally and copy elements of temp[] array to matrix.
1943
Chapter 283. Rotate each ring of matrix anticlockwise by K elements
{
for (int i = m-1; i >= k; --i)
mat[i][l] = temp[tIdx++];
l++;
}
}
}
// Function to spirally traverse matrix and
// rotate each ring of matrix by K elements
// mat[][] --> matrix of elements
// M --> number of rows
// N --> number of columns
void spiralRotate(int mat[][MAX], int M, int N, int k)
{
// Create a temporary array to store the result
int temp[M*N];
/* s - starting row index
m - ending row index
l - starting column index
n - ending column index; */
int m = M, n = N, s = 0, l = 0;
int *start = temp; // Start position of current ring
int tIdx = 0; // Index in temp
while (s < m && l < n)
{
// Initialize end position of current ring
int *end = start;
// copy the first row from the remaining rows
for (int i = l; i < n; ++i)
{
temp[tIdx++] = mat[s][i];
end++;
}
s++;
// copy the last column from the remaining columns
for (int i = s; i < m; ++i)
{
temp[tIdx++] = mat[i][n-1];
end++;
}
n--;
// copy the last row from the remaining rows
1944
Chapter 283. Rotate each ring of matrix anticlockwise by K elements
if (s < m)
{
for (int i = n-1; i >= l; --i)
{
temp[tIdx++] = mat[m-1][i];
end++;
}
m--;
}
/* copy the first column from the remaining columns */
if (l < n)
{
for (int i = m-1; i >= s; --i)
{
temp[tIdx++] = mat[i][l];
end++;
}
l++;
}
// if elements in current ring greater than
// k then rotate elements of current ring
if (end-start > k)
{
// Rotate current ring using revarsal
// algorithm for rotation
reverse(start, start+k);
reverse(start+k, end);
reverse(start, end);
// Reset start for next ring
start = end;
}
else // There are less than k elements in ring
break;
}
// Fill tenp array in original matrix.
fillSpiral(mat, M, N, temp);
}
// Driver program to run the case
int main()
{
// Your C++ Code
int M = 4, N = 4, k = 3;
int mat[][MAX]= {{1, 2, 3, 4},
1945
Chapter 283. Rotate each ring of matrix anticlockwise by K elements
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
spiralRotate(mat, M, N, k);
// print modified matrix
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
return 0;
}
Output:
4 8 12 16
3 10 6 15
2 11 7 14
1 5 9 13
Source
https://www.geeksforgeeks.org/rotate-ring-matrix-anticlockwise-k-elements/
1946
Chapter 284
Input : N = 3, M = 3, K = 2
12 23 34
45 56 67
78 89 91
Output : 23 34 12
56 67 45
89 91 78
Input : N = 2, M = 2, K = 2
1 2
3 4
Output : 1 2
3 4
A simple yet effective approach is to consider each row of the matrix as an array and perform
an array rotation. Which can be done by copying the elements from K to end of array to
starting of array using temporary array. And then the remaining elements from start to K-1
to end of the arryay.
1947
Chapter 284. Rotate the matrix right by K times
C++
1948
Chapter 284. Rotate the matrix right by K times
}
// function to display the matrix
void displayMatrix(int matrix[][M]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
cout << matrix[i][j] << " ";
cout << endl;
}
}
// Driver's code
int main() {
int matrix[N][M] = {{12, 23, 34},
{45, 56, 67},
{78, 89, 91}};
int k = 2;
// rotate matrix by k
rotateMatrix(matrix, k);
// display rotated matrix
displayMatrix(matrix);
return 0;
}
Java
1949
Chapter 284. Rotate the matrix right by K times
{
// copy first M-k elements
// to temporary array
for (int t = 0; t < M - k; t++)
temp[t] = matrix[i][t];
// copy the elements from k
// to end to starting
for (int j = M - k; j < M; j++)
matrix[i][j - M + k] = matrix[i][j];
// copy elements from
// temporary array to end
for (int j = k; j < M; j++)
matrix[i][j] = temp[j - k];
}
}
// function to display the matrix
static void displayMatrix(int matrix[][])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
// Driver code
public static void main (String[] args)
{
int matrix[][] = {{12, 23, 34},
{45, 56, 67},
{78, 89, 91}};
int k = 2;
// rotate matrix by k
rotateMatrix(matrix, k);
// display rotated matrix
displayMatrix(matrix);
}
}
// This code is contributed by Anant Agarwal.
1950
Chapter 284. Rotate the matrix right by K times
Python3
1951
Chapter 284. Rotate the matrix right by K times
for i in range(0, N) :
for j in range(0, M) :
print ("{} " .
format(matrix[i][j]), end = "")
print ()
# Driver code
k = 2
# rotate matrix by k
rotateMatrix(k)
# display rotated matrix
displayMatrix()
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
1952
Chapter 284. Rotate the matrix right by K times
PHP
<?php
// PHP program to rotate
// a matrix right by k times
1953
Chapter 284. Rotate the matrix right by K times
// size of matrix
$M = 3;
$N = 3;
// function to rotate
// matrix by k times
function rotateMatrix(&$matrix, $k)
{
global $M, $N;
// temporary array
// of size M
$temp = array();
// within the size
// of matrix
$k = $k % $M;
for ($i = 0; $i < $N; $i++)
{
// copy first M-k elements
// to temporary array
for ($t = 0;
$t < $M - $k; $t++)
$temp[$t] = $matrix[$i][$t];
// copy the elements from
// k to end to starting
for ($j = $M - $k;
$j < $M; $j++)
$matrix[$i][$j - $M + $k] =
$matrix[$i][$j];
// copy elements from
// temporary array to end
for ($j = $k; $j < $M; $j++)
$matrix[$i][$j] = $temp[$j - $k];
}
}
// function to display
// the matrix
function displayMatrix(&$matrix)
{
global $M, $N;
for ($i = 0; $i < $N; $i++)
1954
Chapter 284. Rotate the matrix right by K times
{
for ($j = 0; $j < $M; $j++)
echo ($matrix[$i][$j]." ");
echo ("\n");
}
}
// Driver code
$matrix = array(array(12, 23, 34),
array(45, 56, 67),
array(78, 89, 91));
$k = 2;
// rotate matrix by k
rotateMatrix($matrix, $k);
// display rotated matrix
displayMatrix($matrix);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
23 34 12
56 67 45
89 91 78
Source
https://www.geeksforgeeks.org/rotate-matrix-right-k-times/
1955
Chapter 285
Input :
77 11 22 3
11 89 1 12
32 11 56 7
11 22 44 33
Output :
3 11 22 77
1 11 12 89
7 11 32 56
11 22 33 44
Input :
8 6 4 5
3 5 2 1
9 7 4 2
7 8 9 5
Output :
4 5 6 8
1 2 3 5
2 4 7 9
5 7 8 9
1956
Chapter 285. Row wise sorting in 2D array
Java
1957
Chapter 285. Row wise sorting in 2D array
Output
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Output
1958
Chapter 285. Row wise sorting in 2D array
1 7 8 9
0 2 3 7
2 3 5 9
1 2 3 6
Source
https://www.geeksforgeeks.org/row-wise-sorting-2d-array/
1959
Chapter 286
Input : 1 2 1
4 5 2
0 5 1
Output : 2
Primary diagonal is 1 5 1
Secondary diagonal is 1 5 0
Two elements (1 and 5) match
in two diagonals and same.
Input : 1 0 0
0 1 0
0 0 1
Output : 1
Primary diagonal is 1 1 1
Secondary diagonal is 0 1 0
Only one element is same.
We can achieve this in O(n) time, O(1) space and only one traversal. We can find current
element in i-th row of primary diagonal as mat[i][i] and i-th element of secondary diagonal
as mat[i][n-i-1].
C++
1960
Chapter 286. Row-wise common elements in two diagonals of a square matrix
Java
1961
Chapter 286. Row-wise common elements in two diagonals of a square matrix
// Driver Code
public static void main(String args[])throws IOException
{
int mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
System.out.println(countCommon(mat, 3));
}
}
// This code is contributed by Anshika Goyal.
Python3
C#
1962
Chapter 286. Row-wise common elements in two diagonals of a square matrix
class GFG {
// Returns count of row wise same
// elements in two diagonals of
// mat[n][n]
static int countCommon(int [,]mat, int n)
{
int res = 0;
for (int i = 0; i < n; i++)
if (mat[i,i] == mat[i,n - i - 1])
res++;
return res;
}
// Driver Code
public static void Main()
{
int [,]mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Console.WriteLine(countCommon(mat, 3));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find common
// elements in two diagonals.
$MAX = 100;
// Returns count of row wise
// same elements in two
// diagonals of mat[n][n]
function countCommon($mat, $n)
{
global $MAX;
$res = 0;
for ($i = 0; $i < $n; $i++)
if ($mat[$i][$i] == $mat[$i][$n - $i - 1])
$res++;
return $res;
}
1963
Chapter 286. Row-wise common elements in two diagonals of a square matrix
// Driver Code
$mat = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
echo countCommon($mat, 3);
// This code is contributed by aj_36
?>
Output :
Source
https://www.geeksforgeeks.org/row-wise-common-elements-two-diagonals-square-matrix/
1964
Chapter 287
Row-wise vs column-wise
traversal of matrix
Difference: If we see according to time complexity, both lead to O(n2 ), but when it comes
to cache level one of the orders access will be faster as compare to other one. It depends
on the language we are using. Like in C, store matrix in row major form so while accessing
the i+1th element after ith , most probably it will lead to a hit, which will further reduce the
time of program.
Following is C code showing the time difference in row major and column major access.
1965
Chapter 287. Row-wise vs column-wise traversal of matrix
int arr[MAX][MAX] = {0};
void rowMajor() {
int i, j;
// accessing element row wise
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
arr[i][j]++;
}
}
}
void colMajor() {
int i, j;
// accessing element column wise
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
arr[j][i]++;
}
}
}
// driver code
int main() {
int i, j;
// Time taken by row major order
clock_t t = clock();
rowMajor();
t = clock() - t;
printf("Row major access time :%f s\n",
t / (float)CLOCKS_PER_SEC);
// Time taken by column major order
t = clock();
colMajor();
t = clock() - t;
printf("Column major access time :%f s\n",
t / (float)CLOCKS_PER_SEC);
return 0;
}
Output:
1966
Chapter 287. Row-wise vs column-wise traversal of matrix
Source
https://www.geeksforgeeks.org/row-wise-vs-column-wise-traversal-matrix/
1967
Chapter 288
A simple solution is to traverse all matrix elements one by one and check if the element
is Saddle Point or not.
An efficient solution is based on below steps.
Traverse all rows one by one and do following for every row i.
1. Find the minimum element of current row and store column index of the minimum
element.
2. Check if the row minimum element is also maximum in its column. We use the stored
column index here.
3. If yes, then saddle point else continue till end of matrix.
1968
Chapter 288. Saddle point in a matrix
C++
1969
Chapter 288. Saddle point in a matrix
}
// Driver code
int main()
{
int mat[MAX][MAX] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
if (findSaddlePoint(mat, n) == false)
cout << "No Saddle Point ";
return 0;
}
Java
1970
Chapter 288. Saddle point in a matrix
// print it
if (k == n)
{
System.out.println("Value of Saddle Point " + min_row);
return true;
}
}
// If Saddle Point not found
return false;
}
// Driver method
public static void main(String[] args)
{
int mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
if (findSaddlePoint(mat, n) == false)
System.out.println("No Saddle Point ");
}
}
C#
1971
Chapter 288. Saddle point in a matrix
{
min_row = mat[i, j];
col_ind = j;
}
}
// Check if the minimum element
// of row is also the maximum
// element of column or not
int k;
for (k = 0; k < n; k++)
// Note that col_ind is fixed
if (min_row < mat[k, col_ind])
break;
// If saddle point is present in this row then
// print it
if (k == n)
{
Console.WriteLine("Value of Saddle Point "
+ min_row);
return true;
}
}
// If Saddle Point not found
return false;
}
// Driver code
public static void Main()
{
int [,] mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
if (findSaddlePoint(mat, n) == false)
Console.WriteLine("No Saddle Point ");
}
}
// This code is contributed by KRV.
PHP
<?php
1972
Chapter 288. Saddle point in a matrix
1973
Chapter 288. Saddle point in a matrix
// Driver code
$mat = array(array(1, 2, 3),
array(4, 5, 6),
array (7, 8, 9));
$n = 3;
if (findSaddlePoint($mat, $n) == false)
echo "No Saddle Point ";
// This code is contributed by anuj_67.
?>
Output :
Exercise :
Can there be more than one Saddle Points in a Matrix?
Improved By : KRV, vt_m
Source
https://www.geeksforgeeks.org/saddle-point-matrix/
1974
Chapter 289
Input : arr[] = {
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9}
}
element=5
Output : Element Found at position (1, 1).
Input : arr[]={
{ 11, 21, 31, 41, 51 },
{ 12, 22, 32, 42, 52 },
{ 13, 23, 33, 43, 53 },
{ 14, 24, 34, 44, 54 },
{ 15, 25, 35, 45, 55 }
}
element=11
A simple solution is to search one by one. Time complexity of this solution is O(n2 ).
A better solution is to use Divide and Conquer to find the element. Time complexity of
this solution is O(n1.58 ). Please refer this article for details.
1975
Chapter 289. Saddleback Search Algorithm in a 2D array
C++
1976
Chapter 289. Saddleback Search Algorithm in a 2D array
Java
1977
Chapter 289. Saddleback Search Algorithm in a 2D array
C#
1978
Chapter 289. Saddleback Search Algorithm in a 2D array
// Driver Code
public static void Main()
{
int [,]mat = {{10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
{50, 60, 70, 80}};
if (search(mat, 5, 4, 29))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Output:
Yes
Source
https://www.geeksforgeeks.org/saddleback-search-algorithm-in-a-2d-array/
1979
Chapter 290
1980
Chapter 290. Search a Word in a 2D Grid of characters
Below diagram shows a bigger grid and presence of different words in it.
1981
Chapter 290. Search a Word in a 2D Grid of characters
1982
Chapter 290. Search a Word in a 2D Grid of characters
Output:
pattern found at 0, 0
pattern found at 0, 8
pattern found at 1, 0
pattern found at 0, 2
pattern found at 0, 10
pattern found at 2, 2
pattern found at 2, 12
Exercise: The above solution only print locations of word. Extend it to print the direction
where word is present.
See this for solution of exercise.
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/search-a-word-in-a-2d-grid-of-characters/
1983
Chapter 291
Please note that this problem is different from Search in a row wise and column wise sorted
matrix. Here matrix is more strictly sorted as first element of a row is greater than last
element of previous row.
A Simple Solution is to one by one compare x with every element of matrix. If matches,
then return position. If we reach end, return -1. Time complexity of this solution is O(n x
m).
An efficient solution is to typecast given 2D array to 1D array, then apply binary search
on the typecasted array.
1984
Chapter 291. Search element in a sorted matrix
Example:
Consider: | 1 2 3 4|
x = 3, mat = | 5 6 7 8| Middle column:
| 9 10 11 12| = {2, 6, 10, 14}
|13 14 15 16| perform binary search on them
since, x < 6, discard the
last 2 rows as 'a' will
not lie in them(sorted matrix)
Now, only two rows are left
| 1 2 3 4|
x = 3, mat = | 5 6 7 8| Check whether element is present
on the middle elements of these
rows = {2, 6}
x != 2 or 6
If not, consider the four sub-parts
1st half of 1st row = {1}, 2nd half of 1st row = {3, 4}
1st half of 2nd row = {5}, 2nd half of 2nd row = {7, 8}
C++
1985
Chapter 291. Search element in a sorted matrix
1986
Chapter 291. Search element in a sorted matrix
// Do binary search in middle column.
// Condition to terminate the loop when the
// 2 desired rows are found
int i_low = 0;
int i_high = n-1;
int j_mid = m/2;
while ((i_low+1) < i_high)
{
int i_mid = (i_low + i_high) / 2;
// element found
if (mat[i_mid][j_mid] == x)
{
cout << "Found at (" << i_mid << ", "
<< j_mid << ")";
return;
}
else if (mat[i_mid][j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
// If element is present on the mid of the
// two rows
if (mat[i_low][j_mid] == x)
cout << "Found at (" << i_low << ","
<< j_mid << ")";
else if (mat[i_low+1][j_mid] == x)
cout << "Found at (" << (i_low+1)
<< ", " << j_mid << ")";
// Ssearch element on 1st half of 1st row
else if (x <= mat[i_low][j_mid-1])
binarySearch(mat, i_low, 0, j_mid-1, x);
// Search element on 2nd half of 1st row
else if (x >= mat[i_low][j_mid+1] &&
x <= mat[i_low][m-1])
binarySearch(mat, i_low, j_mid+1, m-1, x);
// Search element on 1st half of 2nd row
else if (x <= mat[i_low+1][j_mid-1])
binarySearch(mat, i_low+1, 0, j_mid-1, x);
1987
Chapter 291. Search element in a sorted matrix
Java
1988
Chapter 291. Search element in a sorted matrix
else
j_low = j_mid + 1;
}
// element not found
System.out.println ( "Element no found");
}
// Function to perform binary search on the mid
// values of row to get the desired pair of rows
// where the element can be found
static void sortedMatrixSearch(int mat[][], int n,
int m, int x)
{
// Single row matrix
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return;
}
// Do binary search in middle column.
// Condition to terminate the loop when the
// 2 desired rows are found
int i_low = 0;
int i_high = n - 1;
int j_mid = m / 2;
while ((i_low + 1) < i_high)
{
int i_mid = (i_low + i_high) / 2;
// element found
if (mat[i_mid][j_mid] == x)
{
System.out.println ( "Found at (" + i_mid +", "
+ j_mid +")");
return;
}
else if (mat[i_mid][j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
// If element is present on
1989
Chapter 291. Search element in a sorted matrix
C#
// C# implementation to search
// an element in a sorted matrix
using System;
1990
Chapter 291. Search element in a sorted matrix
class GFG
{
// This function does Binary search for x in i-th
// row. It does the search from mat[i][j_low] to
// mat[i][j_high]
static void binarySearch(int [,]mat, int i, int j_low,
int j_high, int x)
{
while (j_low <= j_high)
{
int j_mid = (j_low + j_high) / 2;
// Element found
if (mat[i,j_mid] == x)
{
Console.Write ( "Found at (" + i +
", " + j_mid +")");
return;
}
else if (mat[i,j_mid] > x)
j_high = j_mid - 1;
else
j_low = j_mid + 1;
}
// element not found
Console.Write ( "Element no found");
}
// Function to perform binary search on the mid
// values of row to get the desired pair of rows
// where the element can be found
static void sortedMatrixSearch(int [,]mat, int n,
int m, int x)
{
// Single row matrix
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return;
}
// Do binary search in middle column.
// Condition to terminate the loop when the
// 2 desired rows are found
int i_low = 0;
1991
Chapter 291. Search element in a sorted matrix
int i_high = n - 1;
int j_mid = m / 2;
while ((i_low + 1) < i_high)
{
int i_mid = (i_low + i_high) / 2;
// element found
if (mat[i_mid,j_mid] == x)
{
Console.Write ( "Found at (" + i_mid +
", " + j_mid +")");
return;
}
else if (mat[i_mid,j_mid] > x)
i_high = i_mid;
else
i_low = i_mid;
}
// If element is present on
// the mid of the two rows
if (mat[i_low,j_mid] == x)
Console.Write ( "Found at (" + i_low +
"," + j_mid +")");
else if (mat[i_low + 1,j_mid] == x)
Console.Write ( "Found at (" + (i_low
+ 1) + ", " + j_mid +")");
// Ssearch element on 1st half of 1st row
else if (x <= mat[i_low,j_mid - 1])
binarySearch(mat, i_low, 0, j_mid - 1, x);
// Search element on 2nd half of 1st row
else if (x >= mat[i_low,j_mid + 1] &&
x <= mat[i_low,m - 1])
binarySearch(mat, i_low, j_mid + 1, m - 1, x);
// Search element on 1st half of 2nd row
else if (x <= mat[i_low + 1,j_mid - 1])
binarySearch(mat, i_low + 1, 0, j_mid - 1, x);
// search element on 2nd half of 2nd row
else
binarySearch(mat, i_low + 1, j_mid + 1, m - 1, x);
}
1992
Chapter 291. Search element in a sorted matrix
// Driver program
public static void Main (String[] args)
{
int n = 4, m = 5, x = 8;
int [,]mat = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};
sortedMatrixSearch(mat, n, m, x);
}
}
// This code is contributed by parashar...
Output:
Found at (0,2)
Time complexity: O(log n + log m). O(Log n) time is required to find the two desired rows.
Then O(Log m) time is required for binary search in one of the four parts with size equal
to m/2.
Improved By : parashar
Source
https://www.geeksforgeeks.org/search-element-sorted-matrix/
1993
Chapter 292
A simple solution is to search one by one. Time complexity of this solution is O(n2 ).
A better solution is to use Divide and Conquer to find the element. Time complexity of
this solution is O(n1.58 ). Please refer this article for details.
Below is an efficient solution that works in O(n) time.
1994
Chapter 292. Search in a row wise and column wise sorted matrix
C++
1995
Chapter 292. Search in a row wise and column wise sorted matrix
{
int mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
search(mat, 4, 29);
return 0;
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
1996
Chapter 292. Search in a row wise and column wise sorted matrix
Java
1997
Chapter 292. Search in a row wise and column wise sorted matrix
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
C#
1998
Chapter 292. Search in a row wise and column wise sorted matrix
1999
Chapter 292. Search in a row wise and column wise sorted matrix
PHP
<?php
// PHP program to search an
// element in row-wise and
// column-wise sorted matrix
/* Searches the element $x
in mat[][]. If the element is
found, then prints its position
and returns true, otherwise prints
"not found" and returns false */
function search(&$mat, $n, $x)
{
$i = 0;
$j = $n - 1; // set indexes for
// top right element
while ($i < $n && $j >= 0)
{
if ($mat[$i][$j] == $x)
{
echo "n found at " . $i.
", " . $j;
return 1;
}
if ($mat[$i][$j] > $x)
$j--;
else // if $mat[$i][$j] < $x
$i++;
}
echo "n Element not found";
return 0; // if ( $i==$n || $j== -1 )
}
// Driver Code
$mat = array(array(10, 20, 30, 40),
array(15, 25, 35, 45),
array(27, 29, 37, 48),
array(32, 33, 39, 50));
search($mat, 4, 29);
// This code is contributed
// by ChitraNayal
?>
2000
Chapter 292. Search in a row wise and column wise sorted matrix
Output :
n Found at 2, 1
Source
https://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-matrix/
2001
Chapter 293
C++
2002
Chapter 293. Shift matrix elements row-wise by k
Java
2003
Chapter 293. Shift matrix elements row-wise by k
// matrix.
import java.io.*;
import java.util.*;
public class GFG {
static int N = 4;
// Function to shift first k elements
// of each row of matrix.
static void shiftMatrixByK(int [][]mat,
int k)
{
if (k > N) {
System.out.print("Shifting is"
+ " not possible");
return;
}
int j = 0;
while (j < N) {
// Print elements from index k
for (int i = k; i < N; i++)
System.out.print(mat[j][i] + " ");
// Print elements before index k
for (int i = 0; i < k; i++)
System.out.print(mat[j][i] + " ");
System.out.println();
j++;
}
}
// Driver code
public static void main(String args[])
{
int [][]mat = new int [][]
{ {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16} };
int k = 2;
// Function call
shiftMatrixByK(mat, k);
}
2004
Chapter 293. Shift matrix elements row-wise by k
}
// This code is contributed by Manish Shaw
// (manishshaw1)
Python3
2005
Chapter 293. Shift matrix elements row-wise by k
C#
2006
Chapter 293. Shift matrix elements row-wise by k
int k = 2;
// Function call
shiftMatrixByK(mat, k);
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to shift k
// elements in a matrix.
// Function to shift first k
// elements of each row of matrix.
function shiftMatrixByK($mat, $k)
{
$N = 4;
if ($k > $N)
{
echo ("shifting is not possible\n");
return;
}
$j = 0;
while ($j < $N)
{
// Print elements from index k
for ($i = $k; $i < $N; $i++)
echo ($mat[$j][$i]." ");
// Print elements before index k
for ($i = 0; $i < $k; $i++)
echo ($mat[$j][$i]." ");
echo ("\n");
$j++;
}
}
// Driver code
$mat = array(array(1, 2, 3, 4),
array(5, 6, 7, 8),
array(9, 10, 11, 12),
2007
Chapter 293. Shift matrix elements row-wise by k
Output :
3 4 1 2
7 8 5 6
11 12 9 10
15 16 13 14
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/shift-matrix-elements-k/
2008
Chapter 294
The idea is to BFS (breadth first search) on matrix cells. Note that we can always use BFS
to find shortest path if graph is unweighted.
1. Store each cell as a node with their row, column values and distance from source cell.
2009
Chapter 294. Shortest distance between two cells in a matrix or grid
2010
Chapter 294. Shortest distance between two cells in a matrix or grid
}
}
// applying BFS on matrix cells starting from source
queue<QItem> q;
q.push(source);
visited[source.row][source.col] = true;
while (!q.empty()) {
QItem p = q.front();
q.pop();
// Destination found;
if (grid[p.row][p.col] == 'd')
return p.dist;
// moving up
if (p.row - 1 >= 0 &&
visited[p.row - 1][p.col] == false) {
q.push(QItem(p.row - 1, p.col, p.dist + 1));
visited[p.row - 1][p.col] = true;
}
// moving down
if (p.row + 1 < N &&
visited[p.row + 1][p.col] == false) {
q.push(QItem(p.row + 1, p.col, p.dist + 1));
visited[p.row + 1][p.col] = true;
}
// moving left
if (p.col - 1 >= 0 &&
visited[p.row][p.col - 1] == false) {
q.push(QItem(p.row, p.col - 1, p.dist + 1));
visited[p.row][p.col - 1] = true;
}
// moving right
if (p.col + 1 < M &&
visited[p.row][p.col + 1] == false) {
q.push(QItem(p.row, p.col + 1, p.dist + 1));
visited[p.row][p.col + 1] = true;
}
}
return -1;
}
// Driver code
int main()
2011
Chapter 294. Shortest distance between two cells in a matrix or grid
{
char grid[N][M] = { { '0', '*', '0', 's' },
{ '*', '0', '*', '*' },
{ '0', '*', '*', '*' },
{ 'd', '*', '*', '*' } };
cout << minDistance(grid);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/shortest-distance-two-cells-matrix-grid/
2012
Chapter 295
Input:
mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
{1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }};
Source = {0, 0};
Destination = {3, 4};
Output:
Shortest Path is 11
2013
Chapter 295. Shortest path in a Binary Maze
3. We also maintain a Boolean array visited of same size as our input matrix and initialize
all its elements to false.
(a) We LOOP till queue is not empty
(b) Dequeue front cell from the queue
(c) Return if the destination coordinates have reached.
(d) For each of its four adjacent cells, if the value is 1 and they are not visited yet,
we enqueue it in the queue and also mark them as visited.
2014
Chapter 295. Shortest path in a Binary Maze
2015
Chapter 295. Shortest path in a Binary Maze
Output :
Shortest Path is 11
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Chinmay Singh
2016
Chapter 295. Shortest path in a Binary Maze
Source
https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/
2017
Chapter 296
Input :
+++++++++-
-++++++++-
-------++-
-++++++++-
-++++++++-
-++++-----
------+++-
-++++++++-
+---------
++++++++++
Output :
+++++++++C
P++++++++H
HISTORY++E
Y++++++++M
S++++++++I
I++++MATHS
CIVICS+++T
S++++++++R
+GEOGRAPHY
2018
Chapter 296. Solve the Crossword Puzzle
++++++++++
The approach behind this is to recursively check for each word in the vertical position and
in the horizontal position. Then fill the word in the matrix that can be the best fit in the
corresponding position of the grid, then update the crossword grid by filling the gap with
that word.
2019
Chapter 296. Solve the Crossword Puzzle
return matrix;
}
// this function checks for the current word
// if it can be placed vertically or not
// x -> it represent index of row
// y -> it represent index of column
// currentWord -> it represent the
// current word in word array
vector<string> checkVertical(int x, int y,
vector<string> matrix,
string currentWord)
{
int n = currentWord.length();
for (int i = 0; i < n; i++) {
if (matrix[x + i][y] == '#' ||
matrix[x + i][y] == currentWord[i]) {
matrix[x + i][y] = currentWord[i];
}
else {
// this shows that word
// cannot be placed vertically
matrix[0][0] = '@';
return matrix;
}
}
return matrix;
}
// this function recursively checks for every
// word that can align vertically in one loop
// and in another loop it checks for those words
// that can align horizontally words -> it
// contains all the words to fill in a crossword
// puzzle matrix -> it contain the current
// state of crossword index -> it represent
// the index of current word n -> it represent
// the length of row or column of the square matrix
void solvePuzzle(vector<string>& words,
vector<string> matrix,
int index, int n)
{
if (index < words.size()) {
string currentWord = words[index];
int maxLen = n - currentWord.length();
2020
Chapter 296. Solve the Crossword Puzzle
// loop to check the words that can align vertically.
for (int i = 0; i < n; i++) {
for (int j = 0; j <= maxLen; j++) {
vector<string> temp = checkVertical(j, i,
matrix, currentWord);
if (temp[0][0] != '@') {
solvePuzzle(words, temp, index + 1, n);
}
}
}
// loop to check the words that can align horizontally.
for (int i = 0; i < n; i++) {
for (int j = 0; j <= maxLen; j++) {
vector<string> temp = checkHorizontal(i, j,
matrix, currentWord);
if (temp[0][0] != '@') {
solvePuzzle(words, temp, index + 1, n);
}
}
}
}
else {
// calling of print function to
// print the crossword puzzle
cout << (ways + 1) << " way to solve the puzzle "
<< endl;
printMatrix(matrix, n);
cout << endl;
// increase the ways
ways++;
return;
}
}
// Driver Code
int main()
{
// length of grid
int n1 = 10;
// matrix to hold the grid of puzzle
vector<string> matrix;
2021
Chapter 296. Solve the Crossword Puzzle
Output:
2022
Chapter 296. Solve the Crossword Puzzle
*D********
***MIZORAM
Source
https://www.geeksforgeeks.org/solve-crossword-puzzle/
2023
Chapter 297
Sorting any matrix in a way that its rows, columns and main diagonal are in increasing
order is easy. If we consider matrix elements in sequence according to row-major order and
sort the sequence, we get the desired result.
2024
Chapter 297. Sort a Matrix in all way increasing order
Output:
0 1 2
3 4 5
6 8 9
2025
Chapter 297. Sort a Matrix in all way increasing order
Source
https://www.geeksforgeeks.org/sort-matrix-way-increasing-order/
2026
Chapter 298
Approach: Create a temp[] array of size n^2. Starting with the first row one by one
copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the
elements of temp[] back to the given matrix.
C++
2027
Chapter 298. Sort the given matrix
2028
Chapter 298. Sort the given matrix
Java
2029
Chapter 298. Sort the given matrix
int mat[][] = { { 5, 4, 7 },
{ 1, 3, 8 },
{ 2, 9, 6 } };
int n = 3;
System.out.println("Original Matrix:");
printMat(mat, n);
sortMat(mat, n);
System.out.println("Matrix After Sorting:");
printMat(mat, n);
}
}
// This code is contributed by Nikita Tiwari.
Python3
2030
Chapter 298. Sort the given matrix
for i in range(0, n) :
for j in range(0, n) :
mat[i][j] = temp[k]
k += 1
# Function to print the given matrix
def printMat(mat, n) :
for i in range(0, n) :
for j in range( 0, n ) :
print(mat[i][j] , end = " ")
print()
# Driver program to test above
mat = [ [ 5, 4, 7 ],
[ 1, 3, 8 ],
[ 2, 9, 6 ] ]
n = 3
print( "Original Matrix:")
printMat(mat, n)
sortMat(mat, n)
print("\nMatrix After Sorting:")
printMat(mat, n)
# This code is contributed by Nikita Tiwari.
C#
// C# implementation to
// sort the given matrix
using System;
class GFG {
static int SIZE = 10;
// function to sort the given matrix
static void sortMat(int[, ] mat, int n)
{
2031
Chapter 298. Sort the given matrix
2032
Chapter 298. Sort the given matrix
// This code is contributed by Sam007
Output :
Original Matrix:
5 4 7
1 3 8
2 9 6
Source
https://www.geeksforgeeks.org/sort-given-matrix/
2033
Chapter 299
2034
Chapter 299. Sort the matrix row-wise and column-wise
Algorithm for sorting each row of matrix using C++ STL sort():
C++
2035
Chapter 299. Sort the matrix row-wise and column-wise
Java
2036
Chapter 299. Sort the matrix row-wise and column-wise
2037
Chapter 299. Sort the matrix row-wise and column-wise
Python 3
2038
Chapter 299. Sort the matrix row-wise and column-wise
# function to find
# transpose of the matrix
def transpose(mat, n):
for i in range (n):
for j in range(i + 1, n):
# swapping element at
# index (i, j) by element
# at index (j, i)
t = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = t
# function to sort
# the matrix row-wise
# and column-wise
def sortMatRowAndColWise(mat, n):
# sort rows of mat[][]
sortByRow(mat, n)
# get transpose of mat[][]
transpose(mat, n)
# again sort rows of mat[][]
sortByRow(mat, n)
# again get transpose of mat[][]
transpose(mat, n)
# function to print the matrix
def printMat(mat, n):
for i in range(n):
for j in range(n):
print(str(mat[i][j] ), end = " ")
print();
# Driver Code
mat = [[ 4, 1, 3 ],
[ 9, 6, 8 ],
[ 5, 2, 7 ]]
n = 3
print("Original Matrix:")
printMat(mat, n)
sortMatRowAndColWise(mat, n)
2039
Chapter 299. Sort the matrix row-wise and column-wise
print("\nMatrix After Sorting:")
printMat(mat, n)
# This code is contributed
# by ChitraNayal
C#
2040
Chapter 299. Sort the matrix row-wise and column-wise
// swapping element at
// index (i, j) by
// element at index (j, i)
var temp = mat[i, j];
mat[i, j] = mat[j, i];
mat[j, i] = temp;
}
}
// function to sort
// the matrix row-wise
// and column-wise
static void sortMatRowAndColWise(int [,]mat,
int n)
{
// sort rows of mat[,]
sortByRow(mat, n);
// get transpose of mat[,]
transpose(mat, n);
// again sort rows of mat[,]
sortByRow(mat, n);
// again get transpose of mat[,]
transpose(mat, n);
}
// function to print the matrix
static void printMat(int [,]mat, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(mat[i, j] + " ");
Console.Write("\n");
}
}
// Driver code
public static void Main ()
{
int [,]mat = {{4, 1, 3},
{9, 6, 8},
{5, 2, 7}};
int n = 3;
2041
Chapter 299. Sort the matrix row-wise and column-wise
Console.Write("Original Matrix:\n");
printMat(mat, n);
sortMatRowAndColWise(mat, n);
Console.Write("\nMatrix After Sorting:\n");
printMat(mat, n);
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP implementation to sort
// the matrix row-wise and
// column-wise
$MAX_SIZE = 10;
// function to sort each
// row of the matrix
function sortByRow(&$mat, $n)
{
for ($i = 0; $i < $n; $i++)
// sorting row number 'i'
sort($mat[$i]);
}
// function to find
// transpose of the matrix
function transpose(&$mat, $n)
{
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1;
$j < $n; $j++)
{
// swapping element at index (i, j)
// by element at index (j, i)
$t = $mat[$i][$j];
$mat[$i][$j] = $mat[$j][$i];
$mat[$j][$i] = $t;
}
}
}
2042
Chapter 299. Sort the matrix row-wise and column-wise
// function to sort
// the matrix row-wise
// and column-wise
function sortMatRowAndColWise(&$mat, $n)
{
// sort rows of mat[][]
sortByRow($mat, $n);
// get transpose of mat[][]
transpose($mat, $n);
// again sort rows of mat[][]
sortByRow($mat, $n);
// again get transpose of mat[][]
transpose($mat, $n);
}
// function to print the matrix
function printMat(&$mat, $n)
{
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
echo $mat[$i][$j] . " ";
echo "\n";
}
}
// Driver Code
$mat = array(array( 4, 1, 3 ),
array( 9, 6, 8 ),
array( 5, 2, 7 ));
$n = 3;
echo "Original Matrix:\n";
printMat($mat, $n);
sortMatRowAndColWise($mat, $n);
echo "\nMatrix After Sorting:\n";
printMat($mat, $n);
// This code is contributed
// by ChitraNayal
?>
2043
Chapter 299. Sort the matrix row-wise and column-wise
Output:
Original Matrix:
4 1 3
9 6 8
5 2 7
Source
https://www.geeksforgeeks.org/sort-matrix-row-wise-column-wise/
2044
Chapter 300
Sorting rows of matrix in ascending order followed by columns in descending order - Geeks-
forGeeks
Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns
in descending order.
Examples :
1) Traverse all rows one by one and sort rows in ascending order using simple array sort.
2) Convert matrix to its transpose
3) Again sort all rows, but this time in ascending order.
4) Again convert matrix to its transpose
2045
Chapter 300. Sorting rows of matrix in ascending order followed by columns in descending
order
C++
2046
Chapter 300. Sorting rows of matrix in ascending order followed by columns in descending
order
// order.
sortByRow(mat, n, false);
// again get transpose of mat[][]
transpose(mat, n);
}
// function to print the matrix
void printMat(int mat[][MAX_SIZE], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << mat[i][j] << " ";
cout << endl;
}
}
// Driver program to test above
int main()
{
int n = 3;
int mat[n][MAX_SIZE] = {{3, 2, 1},
{9, 8, 7},
{6, 5, 4}};
cout << "Original Matrix:\n";
printMat(mat, n);
sortMatRowAndColWise(mat, n);
cout << "\nMatrix After Sorting:\n";
printMat(mat, n);
return 0;
}
Java
2047
Chapter 300. Sorting rows of matrix in ascending order followed by columns in descending
order
// function to sort each row of the matrix
// according to the order specified by
// ascending.
static void sortByRow(Integer mat[][], int n,
boolean ascending)
{
for (int i = 0; i < n; i++)
{
if (ascending)
Arrays.sort(mat[i]);
else
Arrays.sort(mat[i],Collections.reverseOrder());
}
}
// function to find transpose of the matrix
static void transpose(Integer mat[][], int n)
{
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
{
// swapping element at index (i, j)
// by element at index (j, i)
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
// function to sort the matrix row-wise
// and column-wise
static void sortMatRowAndColWise(Integer mat[][],
int n)
{
// sort rows of mat[][]
sortByRow(mat, n, true);
// get transpose of mat[][]
transpose(mat, n);
// again sort rows of mat[][] in descending
// order.
sortByRow(mat, n, false);
// again get transpose of mat[][]
transpose(mat, n);
}
2048
Chapter 300. Sorting rows of matrix in ascending order followed by columns in descending
order
// function to print the matrix
static void printMat(Integer mat[][], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
}
// Driver code
public static void main (String[] args)
{
int n = 3;
Integer mat[][] = {{3, 2, 1},
{9, 8, 7},
{6, 5, 4}};
System.out.print("Original Matrix:\n");
printMat(mat, n);
sortMatRowAndColWise(mat, n);
System.out.print("\nMatrix After Sorting:\n");
printMat(mat, n);
}
}
// This code is contributed by Anant Agarwal.
Python3
2049
Chapter 300. Sorting rows of matrix in ascending order followed by columns in descending
order
mat[i].sort()
else:
mat[i].sort(reverse=True)
# function to find
# transpose of the matrix
def transpose(mat, n):
for i in range(n):
for j in range(i + 1, n):
# swapping element at index (i, j)
# by element at index (j, i)
temp = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = temp
# function to sort
# the matrix row-wise
# and column-wise
def sortMatRowAndColWise(mat, n):
# sort rows of mat[][]
sortByRow(mat, n, True)
# get transpose of mat[][]
transpose(mat, n)
# again sort rows of
# mat[][] in descending
# order.
sortByRow(mat, n, False)
# again get transpose of mat[][]
transpose(mat, n)
# function to print the matrix
def printMat(mat, n):
for i in range(n):
for j in range(n):
print(mat[i][j] , " ", end="")
print()
#Driver code
n = 3
mat = [[3, 2, 1],
2050
Chapter 300. Sorting rows of matrix in ascending order followed by columns in descending
order
[9, 8, 7],
[6, 5, 4]]
print("Original Matrix:")
printMat(mat, n)
sortMatRowAndColWise(mat, n)
print("Matrix After Sorting:")
printMat(mat, n)
# This code is contributed
# by Anant Agarwal.
Output :
Original Matrix:
3 2 1
9 8 7
6 5 4
Source
https://www.geeksforgeeks.org/sorting-rows-matrix-ascending-order-followed-sorting-columns-descending-order/
2051
Chapter 301
In this article, we will discuss another representation of the Sparse Matrix which is commonly
referred as the Yale Format.
The CSR (Compressed Sparse Row) or the Yale Format is similar to the Array Representa-
tion (discussed in Set 1) of Sparse Matrix. We represent a matric M (m * n), by three 1-D
arrays or vectors called as A, IA, JA. Let NNZ denote the number of non-zero elements in
M and note that 0-based indexing is used.
• The A vector is of size NNZ and it stores the values of the non-zero elements of the
matrix. The values appear in the order of traversing the matrix row-by-row
• The IA vector is of size m+1 stores the cumulative number of non-zero elements upto
( not including) the i-th row. It is defined by the recursive relation :
– IA[0] = 0
– IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix
• The JA vector stores the column index of each element in the A vector. Thus it is of
size NNZ as well.
2052
Chapter 301. Sparse Matrix Representations | Set 3 ( CSR )
To find the no of non-zero elements in say row i, we perform IA[i+1] – IA[i]. Notice how
this representation is different to the array based implementation where the second vector
stores the row indices of non-zero elements.
The following examples show how these matrixes are represented.
Examples:
Input : 0 0 0 0
5 8 0 0
0 0 3 0
0 6 0 0
Input : 10 20 0 0 0 0
0 30 0 4 0 0
0 0 50 60 70 0
0 0 0 0 0 80
Algorithm
SPARSIFY (MATRIX)
Step 1: Set M to number of rows in MATRIX
Step 2: Set N to number of columns in MATRIX
Step 3: I = 0, NNZ = 0. Declare A, JA, and IA.
Set IA[0] to 0
Step 4: for I = 0 ... N-1
2053
Chapter 301. Sparse Matrix Representations | Set 3 ( CSR )
2054
Chapter 301. Sparse Matrix Representations | Set 3 ( CSR )
Output:
0 0 0 0 1
2055
Chapter 301. Sparse Matrix Representations | Set 3 ( CSR )
5 8 0 0 0
0 0 3 0 0
0 6 0 0 1
A = [ 1 5 8 3 6 1 ]
IA = [ 0 1 3 4 6 ]
JA = [ 4 0 1 2 1 4 ]
Notes
• The sparsity of the matrix = ( Total No of Elements – Number of Non Zero Elements)
/ ( Total No of Elements) or (1 – NNZ/mn ) or ( 1 – size(A)/mn ) .
• The direct array based representation required memory 3 * NNZ wile CSR requires (
2*NNZ + m + 1) memory.
References
https://en.wikipedia.org/wiki/Sparse_matrix
Source
https://www.geeksforgeeks.org/sparse-matrix-representations-set-3-csr/
2056
Chapter 302
Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists) - Geeks-
forGeeks
A matrix is a two-dimensional data object made of m rows and n columns, therefore having
total m x n values. If most of the elements of the matrix have 0 value, then it is called a
sparse matrix.
Why to use Sparse Matrix instead of simple matrix ?
• Storage: There are lesser non-zero elements than zeros and thus lesser memory can
be used to store only those elements.
• Computing time: Computing time can be saved by logically designing a data struc-
ture traversing only non-zero elements..
Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
2057
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)
1. Array representation
2. Linked list representation
2058
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)
int compactMatrix[3][size];
// Making of new matrix
int k = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}
for (int i=0; i<3; i++)
{
for (int j=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);
printf("\n");
}
return 0;
}
Output:
0 0 1 1 3 3
2 4 2 3 1 2
3 4 5 7 2 6
2059
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)
2060
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)
}
else
{
while (temp->next != NULL)
temp = temp->next;
// Create new node dynamically
r = (struct Node *) malloc (sizeof(struct Node));
r->value = non_zero_element;
r->row_position = row_index;
r->column_postion = column_index;
r->next = NULL;
temp->next = r;
}
}
// This function prints contents of linked list
// starting from start
void PrintList(struct Node* start)
{
struct Node *temp, *r, *s;
temp = r = s = start;
printf("row_position: ");
while(temp != NULL)
{
printf("%d ", temp->row_position);
temp = temp->next;
}
printf("\n");
printf("column_postion: ");
while(r != NULL)
{
printf("%d ", r->column_postion);
r = r->next;
}
printf("\n");
printf("Value: ");
while(s != NULL)
{
printf("%d ", s->value);
s = s->next;
}
printf("\n");
2061
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)
}
// Driver of the program
int main()
{
// Assume 4x5 sparse matrix
int sparseMatric[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
/* Start with the empty list */
struct Node* start = NULL;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
// Pass only those values which are non - zero
if (sparseMatric[i][j] != 0)
create_new_node(&start, sparseMatric[i][j], i, j);
PrintList(start);
return 0;
}
Output:
row_position: 0 0 1 1 3 3
column_postion: 2 4 2 3 1 2
Value: 3 4 5 7 2 6
Other representations:
As a Dictionary where row and column numbers are used as keys and values are matrix
entries. This method saves space but sequential access of items is costly.
As a list of list. The idea is to make a list of rows and every item of list contains values.
We can keep list items sorted by column numbers.
Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)
Source
https://www.geeksforgeeks.org/sparse-matrix-representation/
2062
Chapter 303
Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys) -
GeeksforGeeks
Prerequisite : Sparse Matrix and its representations Set 1 (Using Arrays and Linked Lists)
In this post other two methods of sparse matrix representation are discussed.
1. List of Lists
2. Dictionary
2063
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)
2064
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)
2065
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)
{
create_value_node(Sparse_Matrix[i][j], j, &z);
}
}
}
}
//Function display data of LIL
void print_LIL(struct row_list *start)
{
struct row_list *r;
struct value_list *z;
r = start;
// Traversing row list
while (r != NULL)
{
if (r->link_right != NULL)
{
printf("row=%d \n", r->row_number);
z = r->link_right;
// Traversing data list
while (z != NULL)
{
printf("column=%d value=%d \n",
z->column_index, z->value);
z = z->next;
}
}
r = r->link_down;
}
}
//Driver of the program
int main()
{
// Assume 4x5 sparse matrix
int Sparse_Matrix[R][C] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
// Start with the empty List of lists
struct row_list* start = NULL;
2066
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)
//Function creating List of Lists
create_row_list(&start, R, C, Sparse_Matrix);
// Display data of List of lists
print_LIL(start);
return 0;
}
Output:
row = 1
column = 3 value = 3
column = 5 value = 4
row = 2
column = 3 value = 5
column = 4 value = 7
row = 4
column = 2 value = 2
column = 3 value = 6
Dictionary of Keys
An alternative representation of sparse matrix is Dictionary. For the key field of the
dictionary, pair of row and column index is used that maps with the non – zero element of
the matrix. This method saves space but sequential access of items is costly.
In C++, dictionary is defined as map class of STL(Standard Template Library). To know
more about map click the link below:
Basics of map
2067
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
/* Declaration of map where first field(pair of
row and column) represent key and second
field represent value */
map< pair<int,int>, int > new_matrix;
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (Sparse_Matrix[i][j] != 0)
new_matrix[make_pair(i+1,j+1)] =
Sparse_Matrix[i][j] ;
int c = 0;
// Iteration over map
for (auto i = new_matrix.begin(); i != new_matrix.end(); i++ )
{
if (c != i->first.first)
{
cout << "row = " << i->first.first << endl ;
c = i->first.first;
}
cout << "column = " << i->first.second <<" ";
cout << "value = " << i->second << endl;
}
return 0;
}
Output:
row = 1
column = 3 value = 3
column = 5 value = 4
row = 2
column = 3 value = 5
column = 4 value = 7
row = 4
column = 2 value = 2
column = 3 value = 6
2068
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)
Source
https://www.geeksforgeeks.org/sparse-matrix-representations-using-list-lists-dictionary-keys/
2069
Chapter 304
Spiral Pattern
Input : N = 4
Output : 4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
Input : N = 2
Output : 2 2 2
2 1 2
2 2 2
Approach: The common observation is that the square thus formed will be of size (2*N-
1)x(2*N-1). Fill the first row and column, last row and column with N, and then gradually
decrease N and fill the remaining rows and columns similarly. Decrease N every time after
filling 2 rows and 2 columns.
Below is the implementation of the above approach:
C++
2070
Chapter 304. Spiral Pattern
#include <bits/stdc++.h>
using namespace std;
// Function to print the pattern
void pattern(int value)
{
// Declare a square matrix
int row = 2 * value - 1;
int column = 2 * value - 1;
int arr[row][column];
int i, j, k;
for (k = 0; k < value; k++) {
// store the first row
// from 1st column to last column
j = k;
while (j < column - k) {
arr[k][j] = value - k;
j++;
}
// store the last column
// from top to bottom
i = k + 1;
while (i < row - k) {
arr[i][row - 1 - k] = value - k;
i++;
}
// store the last row
// from last column to 1st column
j = column - k - 2;
while (j >= k) {
arr[column - k - 1][j] = value - k;
j--;
}
// store the first column
// from bottom to top
i = row - k - 2;
while (i > k) {
arr[i][k] = value - k;
i--;
}
}
2071
Chapter 304. Spiral Pattern
Java
// Java program to print
// the spiral pattern
class GFG
{
// Function to print the pattern
static void pattern(int value)
{
// Declare a square matrix
int row = 2 * value – 1;
int column = 2 * value – 1;
int[][] arr = new int[row][column];
int i, j, k;
for (k = 0; k < value; k++) { // store the first row // from 1st column to last column j =
k; while (j < column - k) { arr[k][j] = value - k; j++; } // store the last column // from
top to bottom i = k + 1; while (i < row - k) { arr[i][row - 1 - k] = value - k; i++; } // store
the last row // from last column // to 1st column j = column - k - 2; while (j >= k)
{
arr[column – k – 1][j] = value – k;
j–;
}
// store the first column
// from bottom to top
i = row – k – 2;
while (i > k)
{
arr[i][k] = value – k;
i–;
2072
Chapter 304. Spiral Pattern
}
}
// print the pattern
for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { System.out.print(arr[i][j] + ”
”); } System.out.println(); } } // Driver code public static void main(String[] args) { int n
= 5; pattern(n); } } // This code is contributed // by ChitraNayal [tabby title=”Python
3”] # Python 3 program to print # the spiral pattern # Function to print the pattern def
pattern(value): # Declare a square matrix row = 2 * value - 1 column = 2 * value - 1 arr =
[[0 for i in range(row)] for j in range (column)] for k in range( value): # store the first row
# from 1st column to # last column j = k while (j < column - k): arr[k][j] = value - k j +=
1 # store the last column # from top to bottom i = k + 1 while (i < row - k): arr[i][row
- 1 - k] = value - k i += 1 # store the last row # from last column # to 1st column j =
column - k - 2 while j >= k :
arr[column – k – 1][j] = value – k
j -= 1
# store the first column
# from bottom to top
i = row – k – 2
while i > k :
arr[i][k] = value – k
i -= 1
# print the pattern
for i in range(row):
for j in range(column):
print(arr[i][j], end = ” “)
print()
# Driver code
if __name__ == “__main__”:
n=5
pattern(n)
# This code is contributed
# by ChitraNayal
C#
// C# program to print
// the spiral pattern
using System;
class GFG
{
// Function to print the pattern
static void pattern(int value)
{
// Declare a square matrix
int row = 2 * value – 1;
2073
Chapter 304. Spiral Pattern
2074
Chapter 304. Spiral Pattern
5 5 5 5 5 5 5 5 5
5 4 4 4 4 4 4 4 5
5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
Improved By : ChitraNayal
Source
https://www.geeksforgeeks.org/spiral-pattern/
2075
Chapter 305
Input : 1 2 3
4 5 6
7 8 9
Output : Diagonal one: 1 25 81
Diagonal two: 9 25 49
Input : 2 5 7
3 7 2
5 6 9
Output : Diagonal one : 4 49 81
Diagonal two : 49 49 25
Method 1: Firstly we find the diagonal element of the matrix and then we print the square
of that element.
C++
2076
Chapter 305. Squares of Matrix Diagonal Elements
2077
Chapter 305. Squares of Matrix Diagonal Elements
Java
2078
Chapter 305. Squares of Matrix Diagonal Elements
Python3
2079
Chapter 305. Squares of Matrix Diagonal Elements
C#
2080
Chapter 305. Squares of Matrix Diagonal Elements
PHP
<?php
// Simple PHP program to print squares
// of diagonal elements.
//$MAX = 100;
// function of diagonal square
function diagonalsquare($mat, $row,
$column)
{
// This loop is for finding square
// of first diagonal elements
echo "Diagonal one : ";
for ( $i = 0; $i < $row; $i++)
{
for ( $j = 0; $j < $column; $j++)
2081
Chapter 305. Squares of Matrix Diagonal Elements
// if this condition will become true
// then we will get diagonal element
if ($i == $j)
// printing square of diagonal
// element
echo $mat[$i][$j] * $mat[$i][$j]
, " ";
}
// This loop is for finding square of second
// side of diagonal elements
echo " \n\nDiagonal two : ";
for ( $i = 0; $i < $row; $i++)
{
for ($j = 0; $j < $column; $j++)
// if this condition will become
// true then we will get second
// side diagonal element
if ($i + $j == $column - 1)
// printing square of diagonal
// element
echo $mat[$i][$j] * $mat[$i][$j],
" ";
}
}
// Driver code
$mat = array(array( 2, 5, 7 ),
array( 3, 7, 2 ),
array( 5, 6, 9 ) );
diagonalsquare($mat, 3, 3);
// This code is contributed by anuj_67.
?>
Output:
Diagonal one : 4 49 81
Diagonal two : 49 49 25
2082
Chapter 305. Squares of Matrix Diagonal Elements
loop to find the diagonal element and then we print the square of that element.
C++
2083
Chapter 305. Squares of Matrix Diagonal Elements
Java
2084
Chapter 305. Squares of Matrix Diagonal Elements
// This code is contributed by vt_m.
Python3
2085
Chapter 305. Squares of Matrix Diagonal Elements
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
2086
Chapter 305. Squares of Matrix Diagonal Elements
// Driver code
public static void Main ()
{
int [,] mat = new int[,]{{ 2, 5, 7 },
{ 3, 7, 2 },
{ 5, 6, 9 }};
diagonalsquare(mat, 3, 3);
}
}
// This code is contributed by KRV.
PHP
<?php
// Efficient PHP program to print squares of
// diagonal elements.
$MAX = 100;
// function of diagonal square
function diagonalsquare( $mat, $row,
$column)
{
// This loop is for finding of square of
// the first side of diagonal elements
echo " \nDiagonal one : ";
for($i = 0; $i < $row; $i++)
{
// printing direct square of diagonal
// element there is no need to check
// condition
echo $mat[$i][$i] * $mat[$i][$i] , " ";
}
// This loop is for finding square of the
// second side of diagonal elements
echo " \n\nDiagonal two : ";
for ( $i = 0; $i < $row; $i++)
{
// printing direct square of diagonal
// element in the second side
2087
Chapter 305. Squares of Matrix Diagonal Elements
echo $mat[$i][$row - $i - 1] *
$mat[$i][$row - $i - 1]
, " ";
}
}
// Driver code
$mat = array(array(2, 5, 7 ),
array(3, 7, 2 ),
array(5, 6, 9 ));
diagonalsquare($mat, 3, 3);
// This code is contributed by anuj_67.
?>
Output:
Diagonal one : 4 49 81
Diagonal two : 49 49 25
Source
https://www.geeksforgeeks.org/squares-of-matrix-diagonal-elements/
2088
Chapter 306
2089
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation
2090
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation
}
}
}
}
lld*** s = new lld**[10];
for (int i = 0; i < 10; i++) {
switch (i) {
case 0:
s[i] = new lld*[adjL];
for (int j = 0; j < adjL; j++) {
s[i][j] = new lld[adjM];
for (int k = 0; k < adjM; k++) {
s[i][j][k] = Bs[0][1][j][k] - Bs[1][1][j][k];
}
}
break;
case 1:
s[i] = new lld*[adjN];
for (int j = 0; j < adjN; j++) {
s[i][j] = new lld[adjL];
for (int k = 0; k < adjL; k++) {
s[i][j][k] = As[0][0][j][k] + As[0][1][j][k];
}
}
break;
case 2:
s[i] = new lld*[adjN];
for (int j = 0; j < adjN; j++) {
s[i][j] = new lld[adjL];
for (int k = 0; k < adjL; k++) {
s[i][j][k] = As[1][0][j][k] + As[1][1][j][k];
}
}
break;
case 3:
s[i] = new lld*[adjL];
for (int j = 0; j < adjL; j++) {
s[i][j] = new lld[adjM];
for (int k = 0; k < adjM; k++) {
s[i][j][k] = Bs[1][0][j][k] - Bs[0][0][j][k];
}
}
break;
case 4:
s[i] = new lld*[adjN];
for (int j = 0; j < adjN; j++) {
s[i][j] = new lld[adjL];
2091
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation
2092
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation
}
break;
}
}
lld*** p = new lld**[7];
p[0] = Strassen(As[0][0], s[0], adjN, adjL, adjM);
p[1] = Strassen(s[1], Bs[1][1], adjN, adjL, adjM);
p[2] = Strassen(s[2], Bs[0][0], adjN, adjL, adjM);
p[3] = Strassen(As[1][1], s[3], adjN, adjL, adjM);
p[4] = Strassen(s[4], s[5], adjN, adjL, adjM);
p[5] = Strassen(s[6], s[7], adjN, adjL, adjM);
p[6] = Strassen(s[8], s[9], adjN, adjL, adjM);
for (int i = 0; i < adjN; i++) {
for (int j = 0; j < adjM; j++) {
c[i][j] = p[4][i][j] + p[3][i][j] - p[1][i][j] + p[5][i][j];
if (j + adjM < m)
c[i][j + adjM] = p[0][i][j] + p[1][i][j];
if (i + adjN < n)
c[i + adjN][j] = p[2][i][j] + p[3][i][j];
if (i + adjN < n && j + adjM < m)
c[i + adjN][j + adjM] = p[4][i][j] + p[0][i][j] - p[2][i][j] - p[6][i][j];
}
}
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
for (int i = 0; i < adjN; i++) {
delete[] As[x][y][i];
}
delete[] As[x][y];
}
delete[] As[x];
}
delete[] As;
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
for (int i = 0; i < adjL; i++) {
delete[] Bs[x][y][i];
}
delete[] Bs[x][y];
}
delete[] Bs[x];
}
delete[] Bs;
2093
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation
2094
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation
lld** matB;
matB = new lld*[3];
for (int i = 0; i < 3; i++)
matB[i] = new lld[2];
matB[0][0] = 7;
matB[0][1] = 8;
matB[1][0] = 9;
matB[1][1] = 10;
matB[2][0] = 11;
matB[2][1] = 12;
lld** matC = Strassen(matA, matB, 2, 3, 2);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%lld ", matC[i][j]);
}
printf("\n");
}
return 0;
}
Output: 58 64
139 154
Source
https://www.geeksforgeeks.org/strassens-matrix-multiplication-algorithm-implementation/
2095
Chapter 307
Output:
Query1: 11 // Sum between (0, 0) and (1, 1)
Query2: 38 // Sum between (2, 2) and (3, 4)
Query3: 38 // Sum between (1, 2) and (3, 3)
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to first create an auxiliary matrix aux[M][N] such that aux[i][j] stores sum of
elements in submatrix from (0,0) to (i,j). Once aux[][] is constructed, we can compute sum
2096
Chapter 307. Submatrix Sum Queries
of submatrix between (tli, tlj) and (rbi, rbj) in O(1) time. We need to consider aux[rbi][rbj]
and subtract all unncessary elements. Below is complete expression to compute submatrix
sum in O(1) time.
Illustration:
2097
Chapter 307. Submatrix Sum Queries
// Function to preprcess input mat[M][N]. This function
// mainly fills aux[M][N] such that aux[i][j] stores sum
// of elements from (0,0) to (i,j)
int preProcess(int mat[M][N], int aux[M][N])
{
// Copy first row of mat[][] to aux[][]
for (int i=0; i<N; i++)
aux[0][i] = mat[0][i];
// Do column wise sum
for (int i=1; i<M; i++)
for (int j=0; j<N; j++)
aux[i][j] = mat[i][j] + aux[i-1][j];
// Do row wise sum
for (int i=0; i<M; i++)
for (int j=1; j<N; j++)
aux[i][j] += aux[i][j-1];
}
// A O(1) time function to compute sum of submatrix
// between (tli, tlj) and (rbi, rbj) using aux[][]
// which is built by the preprocess function
int sumQuery(int aux[M][N], int tli, int tlj, int rbi,
int rbj)
{
// result is now sum of elements between (0, 0) and
// (rbi, rbj)
int res = aux[rbi][rbj];
// Remove elements between (0, 0) and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1][rbj];
// Remove elements between (0, 0) and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi][tlj-1];
// Add aux[tli-1][tlj-1] as elements between (0, 0)
// and (tli-1, tlj-1) are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1][tlj-1];
return res;
}
// Driver program
2098
Chapter 307. Submatrix Sum Queries
int main()
{
int mat[M][N] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
int aux[M][N];
preProcess(mat, aux);
int tli = 2, tlj = 2, rbi = 3, rbj = 4;
cout << "\nQuery1: " << sumQuery(aux, tli, tlj, rbi, rbj);
tli = 0, tlj = 0, rbi = 1, rbj = 1;
cout << "\nQuery2: " << sumQuery(aux, tli, tlj, rbi, rbj);
tli = 1, tlj = 2, rbi = 3, rbj = 3;
cout << "\nQuery3: " << sumQuery(aux, tli, tlj, rbi, rbj);
return 0;
}
Java
2099
Chapter 307. Submatrix Sum Queries
2100
Chapter 307. Submatrix Sum Queries
preProcess(mat, aux);
int tli = 2, tlj = 2, rbi = 3, rbj = 4;
System.out.print("\nQuery1: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
tli = 0; tlj = 0; rbi = 1; rbj = 1;
System.out.print("\nQuery2: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
tli = 1; tlj = 2; rbi = 3; rbj = 3;
System.out.print("\nQuery3: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
}
}
// This code is contributed by Anant Agarwal.
C#
2101
Chapter 307. Submatrix Sum Queries
aux[i,j] += aux[i,j-1];
return 0;
}
// A O(1) time function to compute sum
// of submatrix between (tli, tlj) and
// (rbi, rbj) using aux[][] which is
// built by the preprocess function
static int sumQuery(int [,]aux, int tli,
int tlj, int rbi, int rbj)
{
// result is now sum of elements
// between (0, 0) and (rbi, rbj)
int res = aux[rbi,rbj];
// Remove elements between (0, 0)
// and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1,rbj];
// Remove elements between (0, 0)
// and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi,tlj-1];
// Add aux[tli-1][tlj-1] as elements
// between (0, 0) and (tli-1, tlj-1)
// are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1,tlj-1];
return res;
}
// Driver code
public static void Main ()
{
int [,]mat = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4}};
int [,]aux = new int[M,N];
preProcess(mat, aux);
int tli = 2, tlj = 2, rbi = 3, rbj = 4;
2102
Chapter 307. Submatrix Sum Queries
Console.Write("\nQuery1: " +
sumQuery(aux, tli, tlj, rbi, rbj));
tli = 0; tlj = 0; rbi = 1; rbj = 1;
Console.Write("\nQuery2: " +
sumQuery(aux, tli, tlj, rbi, rbj));
tli = 1; tlj = 2; rbi = 3; rbj = 3;
Console.Write("\nQuery3: " +
sumQuery(aux, tli, tlj, rbi, rbj));
}
}
// This code is contributed by Sam007.
Output:
Query1: 38
Query2: 11
Query3: 38
Source: https://www.geeksforgeeks.org/amazon-interview-experience-set-241-1-5-years-experience/
This article is contributed by Shivam Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007
Source
https://www.geeksforgeeks.org/submatrix-sum-queries/
2103
Chapter 308
Input : N = 2, K = 4
M = {
{1, 1},
{0, 1}
}
Output : [ 3 1]
[ 2 1]
Explanation:
The 4th term of the series is M2(MT)3 and the value of M2(MT)3
is {{3, 1}, {2, 1}}.
Input : N = 2, K = 5
M = {
2104
Chapter 308. Sudo Placement 2 | Matrix Series
{1, 1},
{0, 1}
}
Output : [7 2]
[3 1]
Explanation:
The 4th term of the series is M3(MT)5 and the value of M3(MT)5
is {{7, 2}, {3, 1}}.
Approach :
It can be observed that the powers of MT are 0, 1, 1, 2, 3, 5, 8….. for the 1st , 2nd , 3rd …..
terms respectively. This pattern for the powers of MT is nothing but the Fibonacci series.
Except for the first term, it can be seen that the powers of M also have the same pattern
but, here the power of M is the same as the power of MT for the previous term.
Since in Kth term MT has a power of fibK , M has the power of fibK – 1 .
Where fibi represents the ith fibonacci number.
Thus, for the Kth term (for K � 1) of the series can be calculated as:
As Fibonacci values increase pretty fast the 45th Fibonacci number is close to 1010 . So the
Kth power cant be calculated by repeated multiplication of the matrices K times. To do this,
efficiently we can calculate the Kth power of the matrix using an idea similar to Modular
Exponentiation.
As in Modular Exponentiation, the power is divider by 2 at every step, here also we follow
the same Divide and conquer strategy except the fact that here we don’t multiply numbers,
instead, here multiplication of matrices is required which can be done in O(N3 ), where N is
the size of the square matrix.
Below program illustrate the above approach:
2105
Chapter 308. Sudo Placement 2 | Matrix Series
int n = A.size();
// Resultant matrix formded after multiplying matrix A and B
vector<vector<int> > result(n, vector<int>(n, 0));
// Matrix Multiplication
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
result[i][j] = (result[i][j] + (A[i][k] * B[k][j]) % mod) % mod;
}
}
}
return result;
}
// Function to find the Kth power of matrix A of size nXn in O(logK)
// similar to Modular Exponentiation
vector<vector<int> > fastpower(vector<vector<int> > A, int n, ll K)
{
// Base Case
if (K == 1)
return A;
// Recursive Case1: If power is Odd
if (K & 1) {
// power(A, K) = power(A, K/2) * power(A, K/2) * A
// when K is odd, Note than in this implementation
// multiply (power(A, K - 1) * A) as in the case
// the power becomes even in the next recursive call
return multiply(A, fastpower(A, n, K - 1));
}
// power(A, K) = power(A, K/2) * power(A, K/2) if K is even
vector<vector<int> > result = fastpower(A, n, K / 2);
return multiply(result, result);
}
// Returns the transpose of the matrix A
vector<vector<int> > transpose(vector<vector<int> > A)
{
int N = A.size();
vector<vector<int> > transposeMatrix(N, vector<int>(N, 0));
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
transposeMatrix[i][j] = A[j][i];
2106
Chapter 308. Sudo Placement 2 | Matrix Series
}
}
return transposeMatrix;
}
// Prints the matrix A
void printMatrix(vector<vector<int> > A)
{
int n = A.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
// Return the Kth term of the series where matrix M
// is a boolean matrix of size n X n
void getKthTerm(vector<vector<int> > M, int n, int K)
{
// precompue fibonacci till the Kth term
ll fibonacci[K + 1];
// ith fibonacci number denotes the power of M' in
// the ith term, M' represents the transpose of M
// 1st term has power of M' as 0 thus fib[0] = 1
fibonacci[1] = 0ll;
fibonacci[2] = 1ll;
for (int i = 3; i <= K; i++) {
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
}
// stores the transpose of Matrix M
vector<vector<int> > transposeM = transpose(M);
// K = 1 and K = 2, is handled separately
if (K == 1) {
printMatrix(M);
}
else if (K == 2) {
printMatrix(transposeM);
}
else {
2107
Chapter 308. Sudo Placement 2 | Matrix Series
Output :
3 1
2 1
7 2
3 1
Source
https://www.geeksforgeeks.org/sudo-placement-2-matrix-series/
2108
Chapter 309
Input :[1 2 3 1
4 5 6 1
7 8 9 1
1 1 1 1]
Output: 16
The maximum cost path is:
(3, 3) -> (3, 2) -> (2, 2) -> (1, 1) -> (0, 0).
Cost pathwise is:
1 + 1 + 9 + 5 = 16.
Input: [1 2
3 4]
Output: 4
Optimal Substructure:
The problem is a variation of Min-Cost problem. The path to reach (0, 0) from (n-1, n-1)
must be through the three cells (i, j-1) or (i-1, j) or (i-1, j-1). A top-down recursive function
will be called, for every value of m and n, check if (m+n) is a power of 2 or not. If it is a
power of 2, then move to cell(m-1, n-1) and add the value at a[m][n]. Hence the cost will
be:
2109
Chapter 309. Sudo Placement[1.5] | Wolfish
If it is not a power of 2, then we can move to two of cells (m-1, n) and (m, n-1). So the cost
will be:
2110
Chapter 309. Sudo Placement[1.5] | Wolfish
2111
Chapter 309. Sudo Placement[1.5] | Wolfish
else if (m == 0 && n == 0)
return 0;
// if the state has been visited previously
else if (dp[m][n] != -1)
return dp[m][n];
else {
// i + j
int num = m + n;
// check if it is a power of 2,
// then only move diagonally
if ((num & (num - 1)) == 0)
return dp[m][n] = a[m][n] + maxCost(a, m - 1, n - 1, dp);
// if not a power of 2
// then move side-wise
else
return dp[m][n] = (a[m][n] + max(maxCost(a, m - 1, n, dp),
maxCost(a, m, n - 1, dp)));
}
}
// Function to return the maximum cost
int answer(int a[][size], int n)
{
int dp[size][size];
memset(dp, -1, sizeof dp);
// calling dp function to get the answer
return maxCost(a, n - 1, n - 1, dp);
}
// Driver Code
int main()
{
int a[][size] = { { 1, 2, 3, 1 },
{ 4, 5, 6, 1 },
{ 7, 8, 9, 1 },
{ 1, 1, 1, 1 } };
int n = 4;
// Function calling to get the answer
cout << answer(a, n);
return 0;
}
2112
Chapter 309. Sudo Placement[1.5] | Wolfish
Source
https://www.geeksforgeeks.org/sudo-placement1-5-wolfish/
2113
Chapter 310
Sudoku | Backtracking-7
Naive Algorithm
The Naive Algorithm is to generate all possible configurations of numbers from 1 to 9 to fill
the empty cells. Try every configuration one by one until the correct configuration is found.
Backtracking Algorithm
Like all other Backtracking problems, we can solve Sudoku by one by one assigning numbers
to empty cells. Before assigning a number, we check whether it is safe to assign. We basically
check that the same number is not present in the current row, current column and current
3X3 subgrid. After checking for safety, we assign the number, and recursively check whether
this assignment leads to a solution or not. If the assignment doesn’t lead to a solution, then
2114
Chapter 310. Sudoku | Backtracking-7
we try next number for the current empty cell. And if none of the number (1 to 9) leads to
a solution, we return false.
Following are C++ and Python implementation for Sudoku problem. It prints the
completely filled grid as output.
C/C++
2115
Chapter 310. Sudoku | Backtracking-7
2116
Chapter 310. Sudoku | Backtracking-7
}
/* Returns a boolean which indicates whether an assigned entry
within the specified 3x3 box matches the given number. */
bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol, int num)
{
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
if (grid[row+boxStartRow][col+boxStartCol] == num)
return true;
return false;
}
/* Returns a boolean which indicates whether it will be legal to assign
num to the given row,col location. */
bool isSafe(int grid[N][N], int row, int col, int num)
{
/* Check if 'num' is not already placed in current row,
current column and current 3x3 box */
return !UsedInRow(grid, row, num) &&
!UsedInCol(grid, col, num) &&
!UsedInBox(grid, row - row%3 , col - col%3, num);
}
/* A utility function to print grid */
void printGrid(int grid[N][N])
{
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
printf("%2d", grid[row][col]);
printf("\n");
}
}
/* Driver Program to test above functions */
int main()
{
// 0 means unassigned cells
int grid[N][N] = {{3, 0, 6, 5, 0, 8, 4, 0, 0},
{5, 2, 0, 0, 0, 0, 0, 0, 0},
{0, 8, 7, 0, 0, 0, 0, 3, 1},
{0, 0, 3, 0, 1, 0, 0, 8, 0},
{9, 0, 0, 8, 6, 3, 0, 0, 5},
{0, 5, 0, 0, 9, 0, 6, 0, 0},
{1, 3, 0, 0, 0, 0, 2, 5, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0}};
2117
Chapter 310. Sudoku | Backtracking-7
Python
2118
Chapter 310. Sudoku | Backtracking-7
for i in range(9):
if(arr[i][col] == num):
return True
return False
# Returns a boolean which indicates whether any assigned entry
# within the specified 3x3 box matches the given number
def used_in_box(arr,row,col,num):
for i in range(3):
for j in range(3):
if(arr[i+row][j+col] == num):
return True
return False
# Checks whether it will be legal to assign num to the given row,col
# Returns a boolean which indicates whether it will be legal to assign
# num to the given row,col location.
def check_location_is_safe(arr,row,col,num):
# Check if 'num' is not already placed in current row,
# current column and current 3x3 box
return not used_in_row(arr,row,num) and not used_in_col(arr,col,num) and not used_in_box(arr,
# Takes a partially filled-in grid and attempts to assign values to
# all unassigned locations in such a way to meet the requirements
# for Sudoku solution (non-duplication across rows, columns, and boxes)
def solve_sudoku(arr):
# 'l' is a list variable that keeps the record of row and col in find_empty_location Function
l=[0,0]
# If there is no unassigned location, we are done
if(not find_empty_location(arr,l)):
return True
# Assigning list values to row and col that we got from the above Function
row=l[0]
col=l[1]
# consider digits 1 to 9
for num in range(1,10):
# if looks promising
if(check_location_is_safe(arr,row,col,num)):
# make tentative assignment
arr[row][col]=num
2119
Chapter 310. Sudoku | Backtracking-7
Output:
3 1 6 5 7 8 4 9 2
5 2 9 1 3 4 7 6 8
4 8 7 6 2 9 5 3 1
2 6 3 4 1 5 9 8 7
9 7 4 8 6 3 1 2 5
8 5 1 7 9 2 6 4 3
1 3 8 9 4 7 2 5 6
6 9 2 3 5 1 8 7 4
7 4 5 2 8 6 3 1 9
2120
Chapter 310. Sudoku | Backtracking-7
References:
http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf
Source
https://www.geeksforgeeks.org/sudoku-backtracking-7/
2121
Chapter 311
This problem can be solved easily using two for loops by iterating whole matrix but we can
solve this problem quickly in python using map() function.
2122
Chapter 311. Sum 2D array in Python using map() function
if __name__ == "__main__":
arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]]
print "Sum = ",findSum(arr)
Output:
26
Output :
[1, 4, 9, 16]
Source
https://www.geeksforgeeks.org/sum-2d-array-python-using-map-function/
2123
Chapter 312
Input: L = 4, B = 3
Output: 54
Input: L = 2, B = 5
Output: 26
2124
Chapter 312. Sum of Area of all possible square inside a rectangle
Now, the number of squares of side 1 will be 12 as there will be two cases one as squares
of 1-unit sides along the horizontal(3) and second case as squares of 1-unit sides along the
vertical(4). That gives us 3*4 = 12 squares.
When the side is 2 units, one case will be as squares of side of 2 units along only one place
horizontally and second case as two places vertically. So the number of squares = 6
2125
Chapter 312. Sum of Area of all possible square inside a rectangle
2126
Chapter 312. Sum of Area of all possible square inside a rectangle
Java
// Java program to calculate the
// sum of area of all possible
// squares that comes inside
// the rectangle
class GFG
{
// Function to calculate the
// sum of area of all possible
// squares that comes inside
// the rectangle
static int calculateAreaSum(int l, int b)
{
int size = 1;
// Square with max size possible
int maxSize = Math.min(l, b);
int totalArea = 0;
for(int i = 1; i <= maxSize; i++) { // calculate total square // of a given size int total-
Squares = (l - size + 1) * (b - size + 1); // calculate area of squares // of a particular size int
area = totalSquares * size * size; // total area totalArea += area; // increment size size++;
} return totalArea; } // Driver Code public static void main(String[] args) { int l = 4, b =
3; System.out.println(calculateAreaSum(l, b)); } } // This code is contributed // by Chi-
traNayal [tabby title=”Python 3”] # Python 3 program to calculate # the sum of area of all
possible # squares that comes inside # the rectangle # Function to calculate the # sum of
area of all possible # squares that comes inside # the rectangle def calculateAreaSum(l, b):
size = 1 # Square with max size possible maxSize = min(l, b) totalArea = 0 for i in range(1,
maxSize + 1 ): # calculate total square # of a given size totalSquares = ((l - size + 1) * (b -
size + 1)) # calculate area of squares # of a particular size area = (totalSquares * size * size)
# total area totalArea += area # increment size size += 1 return totalArea # Driver Code
2127
Chapter 312. Sum of Area of all possible square inside a rectangle
54
Improved By : ChitraNayal
Source
https://www.geeksforgeeks.org/sum-of-area-of-all-possible-square-inside-a-rectangle/
2128
Chapter 313
Input : n = 3
Output : 25
Explanation : spiral matrix =
7 8 9
6 1 2
5 4 3
The sum of diagonals is 7+1+3+9+5 = 25
Input : n = 5
Output : 101
Explanation : spiral matrix of order 5
21 22 23 23 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
The sum of diagonals is 21+7+1+3+13+
25+9+5+17 = 101
If we take a closer look at the spiral matrix of n x n, we can notice that top right corner
element has value n2 . Value of top left corner is (n^2) – (n-1) [Why? not that we move
ant-clockwise in spiral matrix, therefore we get value of top left after subtracting n-1 from
2129
Chapter 313. Sum of both diagonals of a spiral odd-order square matrix
top right]. Similarly values of bottom left corner is (n^2) – 2(n-1) and bottom right corner
is (n^2) – 3(n-1). After adding all the four corners we get 4[(n^2)] – 6(n-1).
Let f(n) be sum of diagonal elements for a n x n matrix. Using above observations, we can
recursively write f(n) as:
From above relation, we can find the sum of all diagonal elements of a spiral matrix with
the help of iterative method.
spiralDiaSum(n)
{
if (n == 1)
return 1;
C++
2130
Chapter 313. Sum of both diagonals of a spiral odd-order square matrix
Java
Python3
2131
Chapter 313. Sum of both diagonals of a spiral odd-order square matrix
return (4 * n*n - 6 * n + 6 +
spiralDiaSum(n-2))
# Driver program
n = 7;
print(spiralDiaSum(n))
# This code is contributed by Anant Agarwal.
C#
PHP
<?php
// PHP program to find sum of
// diagonals of spiral matrix
// function returns sum
// of diagonals
2132
Chapter 313. Sum of both diagonals of a spiral odd-order square matrix
Output :
261
Source
https://www.geeksforgeeks.org/sum-diagonals-spiral-odd-order-square-matrix/
2133
Chapter 314
Sum of matrix element where each elements is integer division of row and column - Geeks-
forGeeks
Consider a N X N matrix where each element is row number divide by column number
(integer division), i.e. mat[i][j] = floor((i+1)/(j+1)) where 0 <= i < n and 0 <= j < n. The
task is to find the sum of all matrix element.
Examples :
Input : N = 2
Output : 4
2 X 2 matrix with given constraint:
1 0
2 1
Sum of matrix element: 4
Input : N = 3
Output : 9
C++
2134
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
Java
2135
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
ans += (i/j);
return ans;
}
// Driven Program
public static void main (String[] args)
{
int N = 2;
System.out.println( findSum(N));
}
}
// This code is contributed by anuj_67.
C#
2136
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find sum of matrix element
// where each element is integer division of
// row and column.
// Return sum of matrix element
// where each element is division
// of its corresponding row and
// column.
function findSum( $n)
{
$ans = 0;
// for rows
for($i = 1; $i <= $n; $i++)
// for columns
for($j = 1; $j <= $n; $j++)
$ans += ($i / $j);
return floor($ans);
}
// Driver Code
$N = 2;
echo findSum($N);
// This code is contributed by anuj_67.
?>
Output:
Method 2 (Efficient):
Let N = 9, matrix will be
2137
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
C++
2138
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
Java
2139
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
// Return sum of matrix element where each
// element is division of its corresponding
// row and column.
static int findSum(int n)
{
int ans = 0, temp = 0, num;
// For each column.
for (int i = 1; i <= n && temp < n; i++)
{
// count the number of elements of
// each column. Initialize to i -1
// because number of zeroes are i - 1.
temp = i - 1;
// For multiply
num = 1;
while (temp < n)
{
if (temp + i <= n)
ans += (i * num);
else
ans += ((n - temp) * num);
temp += i;
num ++;
}
}
return ans;
}
// Driven Program
public static void main (String[] args)
{
int N = 2;
System.out.println(findSum(N));
}
}
// This code is contributed by anuj_67.
C#
2140
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
2141
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find sum of
// matrix element where each
// element is integer divison
// of row and column.
// Return sum of matrix element
// where each element is division
// of its corresponding row and column.
function findSum( $n)
{
$ans = 0; $temp = 0; $num;
// For each column.
for ($i = 1; $i <= $n and
$temp < $n; $i++)
{
// count the number of elements
// of each column. Initialize
// to i -1 because number of
// zeroes are i - 1.
$temp = $i - 1;
// For multiply
$num = 1;
while ($temp < $n)
{
if ($temp + $i <= $n)
$ans += ($i * $num);
else
$ans += (($n - $temp) *
$num);
$temp += $i;
$num ++;
}
}
return $ans;
}
2142
Chapter 314. Sum of matrix element where each elements is integer division of row and
column
// Driver Code
$N = 2;
echo findSum($N);
// This code is contributed by anuj_67.
?>
Output :
Source: http://stackoverflow.com/questions/41094769/sum-of-integer-division-matrix?
rq=1
Improved By : vt_m
Source
https://www.geeksforgeeks.org/sum-matrix-element-element-integer-division-row-column/
2143
Chapter 315
Sum of matrix in which each element is absolute difference of its row and column numbers
- GeeksforGeeks
Given a positive integer n. Consider a matrix of n rows and n columns, in which each
element contain absolute difference of its row number and numbers. The task is to calculate
sum of each element of the matrix.
Examples :
Input : n = 2
Output : 2
Matrix formed with n = 2 with given constraint:
0 1
1 0
Sum of matrix = 2.
Input : n = 3
Output : 8
Matrix formed with n = 3 with given constraint:
0 1 2
1 0 1
2 1 0
Sum of matrix = 8.
2144
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
difference of its corresponding row number and column number. Now, find the sum of each
cell.
Below is the implementation of above idea :
C++
Java
2145
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
import java.io.*;
public class GFG {
// Retuen the sum of matrix in which
// each element is absolute difference
// of its corresponding row and column
// number row
static int findSum(int n)
{
// Generate matrix
int [][]arr = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
arr[i][j] = Math.abs(i - j);
// Compute sum
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum += arr[i][j];
return sum;
}
// Driver Code
static public void main (String[] args)
{
int n = 3;
System.out.println(findSum(n));
}
}
// This code is contributed by vt_m.
C#
2146
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
PHP
<?php
// PHP program to find sum of
// matrix in which each element
// is absolute difference of
// its corresponding row and
// column number row.
// Retuen the sum of matrix
// in which each element
// is absolute difference
// of its corresponding row
// and column number row
function findSum( $n)
{
// Generate matrix
2147
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
$arr =array(array());
for($i = 0; $i < $n; $i++)
for($j = 0; $j < $n; $j++)
$arr[$i][$j] = abs($i - $j);
// Compute sum
$sum = 0;
for($i = 0; $i < $n; $i++)
for ($j = 0; $j < $n; $j++)
$sum += $arr[$i][$j];
return $sum;
}
// Driver Code
$n = 3;
echo findSum($n);
// This code is contributed by anuj_67.
?>
Output:
Method 2 (O(n)):
Consider n = 3, matrix formed will be:
012
101
210
Observe, the main diagonal is always 0 since all i are equal to j. The diagonal just above
and just below will always be 1 because at each cell either i is 1 greater than j or j is 1
greater than i and so on.
Following the pattern we can see that the total sum of all the elements in the matrix will
be, for each i from 0 to n, add i*(n-i)*2.
Below is the implementation of above idea :
C++
2148
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
Java
2149
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
C#
PHP
<?php
// PHP program to find sum of matrix in which
// each element is absolute difference of its
// corresponding row and column number row.
// Return the sum of matrix in which each
// element is absolute difference of its
// corresponding row and column number row
function findSum($n)
{
$sum = 0;
for ( $i = 0; $i < $n; $i++)
$sum += $i * ($n - $i);
return 2 * $sum;
}
2150
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
// Driver Code
$n = 3;
echo findSum($n);
// This code is contributed by anuj_67.
?>
Output:
Method 3 (Trick):
Consider n = 3, matrix formed will be:
012
101
210
So, sum = 1 + 1 + 1 + 1 + 2 + 2.
On Rearranging, 1 + 2 + 1 + 2 + 2 = 1 + 2 + 1 + 22 .
So, in every case we can rearrange the sum of matrix so that the answer always will be sum
of first n – 1 natural number and sum of square of first n – 1 natural number.
C++
2151
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
sum += (n*(n+1))/2;
sum += (n*(n+1)*(2*n + 1))/6;
return sum;
}
// Driven Program
int main()
{
int n = 3;
cout << findSum(n) << endl;
return 0;
}
Java
C#
2152
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
PHP
<?php
// PHP program to find sum of
// matrix in which each element
// is absolute difference of its
// corresponding row and column
// number row.
// Retuen the sum of matrix in
// which each element is absolute
// difference of its corresponding
// row and column number row
function findSum($n)
{
$n--;
$sum = 0;
$sum += ($n * ($n + 1)) / 2;
$sum += ($n * ($n + 1) *
(2 * $n + 1)) / 6;
2153
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers
return $sum;
}
// Driver Code
$n = 3;
echo findSum($n) ;
// This code is contributed
// by nitin mittal.
?>
Output :
Source:
https://stackoverflow.com/questions/42043708/sum-of-matrix-in-which-each-element-is-absolute-difference-of-row-
Improved By : vt_m, nitin mittal
Source
https://www.geeksforgeeks.org/sum-matrix-element-absolute-difference-row-column-numbers/
2154
Chapter 316
Input : 2 5 7
3 7 2
5 6 9
Output : Sum of middle row = 12
Sum of middle column = 18
Input : 1 3 5 6 7
3 5 3 2 1
1 2 3 4 5
7 9 2 1 6
9 1 5 3 2
Output : Sum of middle row = 15
Sum of middle column = 18
CPP
2155
Chapter 316. Sum of middle row and column in Matrix
void middlesum(int mat[][MAX], int n)
{
int row_sum = 0, col_sum = 0;
//loop for sum of row
for (int i = 0; i < n; i++)
row_sum += mat[n / 2][i];
cout << "Sum of middle row = "
<< row_sum<<endl;
//loop for sum of column
for (int i = 0; i < n; i++)
col_sum += mat[i][n / 2];
cout << "Sum of middle column = "
<< col_sum;
}
// Driver function
int main()
{
int mat[][MAX] = {{2, 5, 7},
{3, 7, 2},
{5, 6, 9}};
middlesum(mat, 3);
return 0;
}
Java
2156
Chapter 316. Sum of middle row and column in Matrix
Python3
2157
Chapter 316. Sum of middle row and column in Matrix
C#
2158
Chapter 316. Sum of middle row and column in Matrix
PHP
<?php
// PHP program to find sum of
// middle row and column in matrix
function middlesum( $mat, $n)
{
$row_sum = 0; $col_sum = 0;
//loop for sum of row
for ( $i = 0; $i < $n; $i++)
$row_sum += $mat[$n / 2][$i];
echo "Sum of middle row = "
, $row_sum,"\n";
//loop for sum of column
for ( $i = 0; $i < $n; $i++)
$col_sum += $mat[$i][$n / 2];
echo "Sum of middle column = "
, $col_sum;
}
// Driver function
$mat = array(array(2, 5, 7),
array(3, 7, 2),
array(5, 6, 9));
middlesum($mat, 3);
// This code is contributed by anuj_67.
2159
Chapter 316. Sum of middle row and column in Matrix
?>
Output:
Source
https://www.geeksforgeeks.org/sum-middle-row-column-matrix/
2160
Chapter 317
Input : {6, 5, 4}
{1, 2, 5}
{7, 9, 7}
Output :
Upper sum is 29
Lower sum is 32
The solution is quite simple, we just need to traverse the matrix and calculate the sum for
upper and lower triangles accordingly.
C++
2161
Chapter 317. Sum of upper triangle and lower triangle
int i, j;
int upper_sum = 0;
int lower_sum = 0;
/*to calculate sum of upper triangle*/
for (i = 0; i < r; i++)
for (j = 0; j < c; j++) {
if (i <= j) {
upper_sum += mat[i][j];
}
}
printf("Upper sum is %d\n", upper_sum);
/*to calculate sum of lower*/
for (i = 0; i < r; i++)
for (j = 0; j < c; j++) {
if (j <= i) {
lower_sum += mat[i][j];
}
}
printf("Lower sum is %d", lower_sum);
}
/*driver function*/
int main()
{
int r = 3;
int c = 3;
/*giving the matrix*/
int mat[3][3] = {{ 6, 5, 4 },
{ 1, 2, 5 },
{ 7, 9, 7 }};
/*calling the function*/
sum(mat, r, c);
return 0;
}
Java
2162
Chapter 317. Sum of upper triangle and lower triangle
2163
Chapter 317. Sum of upper triangle and lower triangle
C#
2164
Chapter 317. Sum of upper triangle and lower triangle
int c = 3;
/*giving the matrix*/
int [,]mat = {{6, 5, 4},
{1, 2, 5},
{7, 9, 7}};
/*calling the function*/
sum(mat, r, c);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to calculate the sum
// of upper and lower triangle
// function to calculate sum
function sum($mat, $r, $c)
{
$upper_sum = 0;
$lower_sum = 0;
/* to calculate sum of
upper triangle */
for ($i = 0; $i < $r; $i++)
for ($j = 0; $j < $c; $j++)
{
if ($i <= $j)
{
$upper_sum += $mat[$i][$j];
}
}
echo "Upper sum is ". $upper_sum."\n";
/* to calculate sum of lower */
for ($i = 0; $i < $r; $i++)
for ($j = 0; $j < $c; $j++)
{
if ($j <= $i)
{
$lower_sum += $mat[$i][$j];
}
2165
Chapter 317. Sum of upper triangle and lower triangle
}
echo "Lower sum is ". $lower_sum;
}
// Driver Code
$r = 3;
$c = 3;
/*giving the matrix*/
$mat = array(array(6, 5, 4),
array(1, 2, 5),
array(7, 9, 7));
/*calling the function*/
sum($mat, $r, $c);
// This code is contributed by Sam007
?>
Output :
Upper sum is 29
Lower sum is 32
Source
https://www.geeksforgeeks.org/sum-upper-triangle-lower-triangle/
2166
Chapter 318
Output:
Query1: 11 // Sum between (0, 0) and (1, 1)
Query2: 38 // Sum between (2, 2) and (3, 4)
Query3: 38 // Sum between (1, 2) and (3, 3)
Naive Algorithm:
2167
Chapter 318. Summed Area Table – Submatrix Summation
We can loop all the queries and calculate each query in O (q*(N*M)) worst case which is
too large for a large range of numbers.
Optimized Solution :
Summed Area Table can reduce this type of query into preprocessing time of O(M*N) and
each query will execute in O(1).
Summed Area Table is a data structure and algorithm for quickly and efficiently generating
the sum of values in a rectangular subset of a grid.
The value at any point (x, y) in the summed area table is just the sum of all the values
above and to the left of (x, y), inclusive :
Source
https://www.geeksforgeeks.org/summed-area-table-submatrix-summation/
2168
Chapter 319
Example :
Input : 0 1 2
3 4 5
6 7 8
Output : 2 1 0
3 4 5
8 7 6
Approach :
The Simple thing one should know is that the indexes of Primary or Major diagonal are
same i.e. lets say A is matrix then A[1][1] will be a Major Diagonal element and sum of
indexes of Minor Diagonal is equal to size of Matrix. Lets say A is a matrix of size 3 then
A[1][2] will be Minor Diagonal element.
2169
Chapter 319. Swap major and minor diagonals of a square matrix
C++
Java
2170
Chapter 319. Swap major and minor diagonals of a square matrix
Python3
2171
Chapter 319. Swap major and minor diagonals of a square matrix
# Displaying modified matrix
for i in range(N):
for j in range(N):
print(matrix[i][j], end = ' ')
print()
C#
// C# implementation to swap
// diagonal of a matrix
using System;
class Gfg {
static int N = 3;
// Function to swap diagonal of matrix
static void swapDiagonal(int [,]matrix) {
for (int i = 0; i < N; i++) {
int temp = matrix[i,i];
matrix[i,i] = matrix[i,N - i - 1];
matrix[i,N - i - 1] = temp;
}
}
// Driver function
public static void Main() {
int [,]matrix = {{0, 1, 2},
{3, 4, 5},
{6, 7, 8}};
swapDiagonal(matrix);
// Displaying modified matrix
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
Console.Write(matrix[i,j] + " ");
Console.WriteLine();
}
}
}
// This code is contributed by vt_m.
PHP
<?php
2172
Chapter 319. Swap major and minor diagonals of a square matrix
Output :
2 1 0
3 4 5
8 7 6
2173
Chapter 319. Swap major and minor diagonals of a square matrix
Source
https://www.geeksforgeeks.org/swap-major-minor-diagonals-square-matrix/
2174
Chapter 320
2175
Chapter 320. System of Linear Equations in three variables using Cramer’s Rule
Example
2176
Chapter 320. System of Linear Equations in three variables using Cramer’s Rule
[x = D1 /D = 1], [y = D2 /D = 2], [z = D3 /D = 3]
2177
Chapter 320. System of Linear Equations in three variables using Cramer’s Rule
2178
Chapter 320. System of Linear Equations in three variables using Cramer’s Rule
return 0;
}
Output:
D is : -2.000000
D1 is : -2.000000
D2 is : -4.000000
D3 is : -6.000000
Value of x is : 1.000000
Value of y is : 2.000000
Value of z is : 3.000000
Source
https://www.geeksforgeeks.org/system-linear-equations-three-variables-using-cramers-rule/
2179
Chapter 321
2180
Chapter 321. The Celebrity Problem
T(N) = O(N2 ). You may try writing pseudo code to check your recursion skills.
Method 3 (Using Stack)
The graph construction takes O(N2 ) time, it is similar to brute force search. In case of
recursion, we reduce the problem instance by not more than one, and also combine step
may examine M-1 persons (M – instance size).
We have following observation based on elimination technique (Refer Polya’s How to Solve
It book).
We will discard N elements utmost (Why?). If the celebrity is present in the party, we will
call HaveAcquaintance() 3(N-1) times. Here is code using stack.
C++
2181
Chapter 321. The Celebrity Problem
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
int findCelebrity(int n)
{
// Handle trivial
// case of size = 2
stack<int> s;
int C; // Celebrity
// Push everybody to stack
for (int i = 0; i < n; i++)
s.push(i);
// Extract top 2
int A = s.top();
s.pop();
int B = s.top();
s.pop();
// Find a potential celevrity
while (s.size() > 1)
{
if (knows(A, B))
{
A = s.top();
s.pop();
}
else
{
B = s.top();
s.pop();
}
}
// Potential candidate?
C = s.top();
s.pop();
// Last candidate was not
// examined, it leads one
// excess comparison (optimize)
if (knows(C, B))
C = B;
if (knows(C, A))
2182
Chapter 321. The Celebrity Problem
C = A;
// Check if C is actually
// a celebrity or not
for (int i = 0; i < n; i++)
{
// If any person doesn't
// know 'a' or 'a' doesn't
// know any person, return -1
if ( (i != C) &&
(knows(C, i) ||
!knows(i, C)) )
return -1;
}
return C;
}
// Driver code
int main()
{
int n = 4;
int id = findCelebrity(n);
id == -1 ? cout << "No celebrity" :
cout << "Celebrity ID " << id;
return 0;
}
Java
2183
Chapter 321. The Celebrity Problem
true :
false;
return res;
}
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
static int findCelebrity(int n)
{
Stack<Integer> st = new Stack<>();
int c;
// Step 1 :Push everybody
// onto stack
for (int i = 0; i < n; i++)
{
st.push(i);
}
while (st.size() > 1)
{
// Step 2 :Pop off top
// two persons from the
// stack, discard one
// person based on return
// status of knows(A, B).
int a = st.pop();
int b = st.pop();
// Step 3 : Push the
// remained person onto stack.
if (knows(a, b))
{
st.push(b);
}
else
st.push(a);
}
c = st.pop();
// Step 5 : Check if the last
// person is celebrity or not
for (int i = 0; i < n; i++)
{
// If any person doesn't
2184
Chapter 321. The Celebrity Problem
Output :
Celebrity ID 2
Complexity O(N). Total comparisons 3(N-1). Try the above code for successful MATRIX
{{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}}.
Note: You may think that why do we need a new graph as we already have access to input
matrix. Note that the matrix MATRIX used to help the hypothetical function HaveAc-
quaintance(A, B), but never accessed via usual notation MATRIX[i, j]. We have access to
the input only through the function HaveAcquiantance(A, B). Matrix is just a way to code
the solution. We can assume the cost of hypothetical function as O(1).
If still not clear, assume that the function HaveAcquiantance accessing information stored
in a set of linked lists arranged in levels. List node will have next and nextLevel pointers.
Every level will have N nodes i.e. an N element list, next points to next node in the current
level list and the nextLevel pointer in last node of every list will point to head of next level
list. For example the linked list representation of above matrix looks like,
L0 0->0->1->0
|
2185
Chapter 321. The Celebrity Problem
L1 0->0->1->0
|
L2 0->0->1->0
|
L3 0->0->1->0
The function HaveAcquanintance(i, j) will search in the list for j-th node in the i-th level.
Out goal is to minimize calls to HaveAcquanintance function.
Method 4 (Using two Pointers)
The idea is to use two pointers, one from start and one from the end. Assume the start
person is A, and the end person is B. If A knows B, then A must not be the celebrity.
Else, B must not be the celebrity. We will find a celebrity candidate at the end of the
loop. Go through each person again and check whether this is the celebrity. Below is C++
implementation.
C++
2186
Chapter 321. The Celebrity Problem
Java
2187
Chapter 321. The Celebrity Problem
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 } };
// Returns true if a knows
// b, false otherwise
static boolean knows(int a, int b)
{
boolean res = (MATRIX[a][b] == 1) ?
true :
false;
return res;
}
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
static int findCelebrity(int n)
{
// Initialize two pointers
// as two corners
int a = 0;
int b = n - 1;
// Keep moving while
// the two pointers
// don't become same.
while (a < b)
{
if (knows(a, b))
a++;
else
b--;
}
// Check if a is actually
// a celebrity or not
for (int i = 0; i < n; i++)
{
// If any person doesn't
// know 'a' or 'a' doesn't
// know any person, return -1
if (i != a && (knows(a, i) ||
!knows(i, a)))
return -1;
}
return a;
}
2188
Chapter 321. The Celebrity Problem
// Driver Code
public static void main(String[] args)
{
int n = 4;
int result = findCelebrity(n);
if (result == -1)
{
System.out.println("No Celebrity");
}
else
System.out.println("Celebrity ID " +
result);
}
}
// This code is contributed by Rishabh Mahrsee
C#
// C# program to find
// celebrity using two
// pointers
using System;
class GFG
{
// Person with 2 is celebrity
static int [,]MATRIX = {{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 }};
// Returns true if a knows
// b, false otherwise
static bool knows(int a, int b)
{
bool res = (MATRIX[a, b] == 1) ?
true :
false;
return res;
}
// Returns -1 if celebrity
// is not present. If present,
// returns id (value from 0 to n-1).
static int findCelebrity(int n)
{
2189
Chapter 321. The Celebrity Problem
PHP
2190
Chapter 321. The Celebrity Problem
<?php
// PHP program to find
// celebrity in O(n) time
// and O(1) extra space
// Max # of persons
// in the party $N = 8;
// Person with 2 is celebrity
$MATRIX = array(array(0, 0, 1, 0),
array(0, 0, 1, 0),
array(0, 0, 0, 0),
array(0, 0, 1, 0));
function knows( $a, $b)
{
global $MATRIX;
return $MATRIX[$a][$b];
}
// Returns id of celebrity
function findCelebrity( $n)
{
// Initialize two
// pointers as two corners
$a = 0;
$b = $n - 1;
// Keep moving while
// the two pointers
// don't become same.
while ($a < $b)
{
if (knows($a, $b))
$a++;
else
$b--;
}
// Check if a is actually
// a celebrity or not
for ( $i = 0; $i < $n; $i++)
{
// If any person doesn't
// know 'a' or 'a' doesn't
// know any person, return -1
if ( ($i != $a) and
2191
Chapter 321. The Celebrity Problem
Output :
Celebrity ID 2
Source
https://www.geeksforgeeks.org/the-celebrity-problem/
2192
Chapter 322
Input : mat[][] = {0 0 0 0
1 0 0 1
0 1 1 0
0 1 0 0}
Output : 20
First four zeros are surrounded by only
one 1. So coverage for zeros in first
row is 1 + 1 + 1 + 1
Zeros in second row are surrounded by
three 1's. Note that there is no 1 above.
There are 1's in all other three directions.
Coverage of zeros in second row = 3 + 3.
Similarly counting for others also, we get
overall count as below.
1 + 1 + 1 + 1 + 3 + 3 + 2 + 2 + 2 + 2 + 2 = 20
Input : mat[][] = {1 1 1 0
1 0 0 1}
Output : 8
Coverage of first zero is 2
Coverages of other two zeros is 3
2193
Chapter 322. Total coverage of all zeros in a binary matrix
Total coverage = 2 + 3 + 3 = 8
A simple solution to solve this problem is by counting ones around zeros independently
i.e. we run loop four times in each direction for each cell for the given matrix. Whenever
we find a 1 in any loop, we break the loop and increment result by 1.
An efficient solution is to do following.
1. Traverse all rows from left to right, increment result if a 1 is already seen (in current
traversal) and current element is 0.
2. Traverse all rows from right to left, increment result if a 1 is already seen (in current
traversal) and current element is 0.
3. Traverse all columns from top to bottom, increment result if a 1 is already seen (in
current traversal) and current element is 0.
4. Traverse all columns from bottom to top, increment result if a 1 is already seen (in
current traversal) and current element is 0.
In below code a Boolean variable isOne is taken, which is made true as soon as a one is
encountered in current traversal, for all zeros after that iteration, result is incremented by
one, same procedure is applied in all four directions to get final answer. We reset isOne to
false after every traversal.
C++
2194
Chapter 322. Total coverage of all zeros in a binary matrix
isOne = true;
// If 0 is found and we have found
// a 1 before.
else if (isOne)
res++;
}
// Repeat the above process for right to
// left direction.
isOne = false;
for (int j = C-1; j >= 0; j--)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
// Traversing across columms for up and down
// directions.
for (int j = 0; j < C; j++)
{
bool isOne = false; // 1 is not seen yet
for (int i = 0; i < R; i++)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
isOne = false;
for (int i = R-1; i >= 0; i--)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
return res;
}
// Driver code to test above methods
int main()
{
2195
Chapter 322. Total coverage of all zeros in a binary matrix
Java
2196
Chapter 322. Total coverage of all zeros in a binary matrix
else if (isOne)
res++;
}
// Repeat the above
// process for right
// to left direction.
isOne = false;
for (int j = C - 1; j >= 0; j--)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
// Traversing across columms
// for up and down directions.
for (int j = 0; j < C; j++)
{
// 1 is not seen yet
boolean isOne = false;
for (int i = 0; i < R; i++)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
isOne = false;
for (int i = R - 1; i >= 0; i--)
{
if (mat[i][j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
return res;
}
// Driver code
static public void main (String[] args)
{
int [][]mat = {{0, 0, 0, 0},
{1, 0, 0, 1},
2197
Chapter 322. Total coverage of all zeros in a binary matrix
{0, 1, 1, 0},
{0, 1, 0, 0}};
System.out.println(
getTotalCoverageOfMatrix(mat));
}
}
// This code is contributed by anuj_67.
C#
2198
Chapter 322. Total coverage of all zeros in a binary matrix
isOne = false;
for (int j = C-1; j >= 0; j--)
{
if (mat[i,j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
// Traversing across columms
// for up and down directions.
for (int j = 0; j < C; j++)
{
// 1 is not seen yet
bool isOne = false;
for (int i = 0; i < R; i++)
{
if (mat[i,j] == 1)
isOne = true;
else if (isOne)
res++;
}
isOne = false;
for (int i = R-1; i >= 0; i--)
{
if (mat[i,j] == 1)
isOne = true;
else if (isOne)
res++;
}
}
return res;
}
// Driver code to test above methods
static public void Main ()
{
int [,]mat = {{0, 0, 0, 0},
{1, 0, 0, 1},
{0, 1, 1, 0},
{0, 1, 0, 0}};
Console.WriteLine(getTotalCoverageOfMatrix(mat));
}
}
2199
Chapter 322. Total coverage of all zeros in a binary matrix
Output:
20
Source
https://www.geeksforgeeks.org/total-coverage-zeros-binary-matrix/
2200
Chapter 323
Input : m[][] = { { 1, 2 },
{ 1, 3 } }
Output : 8
Explanation : Decreasing paths are { 1 }, { 1 }, { 2 }, { 3 },
{ 2, 1 }, { 3, 1 }, { 3, 2 }, { 3, 2, 1 }
Input : m[][] = { { 1, 2, 3 },
{ 1, 3, 4 },
{ 1, 5, 6 } }
Output : 41
The idea to solve this problem is to use Dynamic Programming. Declare a dp[][] array,
where dp[i][j] stores the number of decreasing path that can be formed from cell
(i, j). So, we will define a recursive function to evaluate the number of decreasing path
with parameters, say i, j, the row number and column number of the current cell. Make
every possible move from the cell(i,j) and keep a count of the total number of paths. First,
we will check in the function that the number of decreasing paths for input position (i, j) is
already calculated or not. If yes, return the value dp[i][j] else find the number of decreasing
sequence in allowed four directions and return the value. Meanwhile, we will also store the
2201
Chapter 323. Total number of decreasing paths in a matrix
number of decreasing for intermediate cells. Since DP[i][j] stores the number of decreasing
paths for every cell, so the summation of all the cells of DP[][] will answer to count of
decreasing paths in the complete matrix.
Below is the implementation of the above approach:
C++
2202
Chapter 323. Total number of decreasing paths in a matrix
Java
2203
Chapter 323. Total number of decreasing paths in a matrix
2204
Chapter 323. Total number of decreasing paths in a matrix
C#
2205
Chapter 323. Total number of decreasing paths in a matrix
2206
Chapter 323. Total number of decreasing paths in a matrix
{
int[,] dp = new int[n, n];
// Initalising dp[][] to -1.
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dp[i, j] = -1;
int sum = 0;
// Calculating number of
// decreasing path from each cell.
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum += CountDecreasingPathsCell(mat, dp,
n, i, j);
return sum;
}
// Driver code
static public void Main ()
{
int n = 2;
int[,] mat= {{1, 2},
{1, 3}};
// function call that returns the
// count of decreasing paths in a matrix
Console.WriteLine(countDecreasingPathsMatrix(n, mat));
}
}
// This code is contributed by vij.
Output:
2207
Chapter 323. Total number of decreasing paths in a matrix
Source
https://www.geeksforgeeks.org/total-number-of-decreasing-paths-in-a-matrix/
2208
Chapter 324
* * * ^ * * *
* * * | * * *
* * * | * * *
* * * | * * *
* * * *
* * * *
* * * *
-- - - >
* * * *
* * * *
* * * *
The idea is simple. Transform each row of source matrix into required column of final image.
We will use an auxiliary buffer to transform the image.
From the above picture, we can observe that
2209
Chapter 324. Turn an image by 90 degree
Transformations
If you have not attempted, atleast try your pseudo code now.
It will be easy to write our pseudo code. In C/C++ we will usually traverse matrix on
row major order. Each row is transformed into different column of final image. We need to
construct columns of final image. See the following algorithm (transformation)
Note that there are various ways to implement the algorithm based on traversal of matrix,
row major or column major order. We have two matrices and two ways (row and column ma-
jor) to traverse each matrix. Hence, there can atleast be 4 different ways of transformation
of source matrix into final matrix.
Code:
2210
Chapter 324. Turn an image by 90 degree
2211
Chapter 324. Turn an image by 90 degree
{5,6,7,8},
{9,10,11,12}};
unsigned int *pSource;
unsigned int *pDestination;
unsigned int m, n;
// setting initial values
// and memory allocation
m = 3, n = 4, pSource = (unsigned int *)image;
pDestination =
(unsigned int *)malloc
(sizeof(int) * m * n);
// process each buffer
displayMatrix(pSource, m, n);
rotate(pSource, pDestination, m, n);
displayMatrix(pDestination, n, m);
free(pDestination);
getchar();
return 0;
}
Output :
1 2 3 4
5 6 7 8
9 10 11 12
9 5 1
10 6 2
11 7 3
12 8 4
2212
Chapter 324. Turn an image by 90 degree
Compiled by Venki. Please write comments if you find anything incorrect, or you want to
share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/turn-an-image-by-90-degree/
2213
Chapter 325
Input : mat[][] = {
{0, 0, 0, 0, 0, 0, 1}
{0, 1, 0, 0, 0, 0, 0}
{0, 0, 0, 0, 0, 1, 0}
{1, 0, 0, 0, 0, 0, 0}
{0, 0, 1, 0, 0, 0, 1}
Output : 3
2214
Chapter 325. Unique cells in a binary matrix
2215
Chapter 325. Unique cells in a binary matrix
PHP
<?php
// PHP program to count
// unique cells in a matrix
$MAX = 100;
// Returns true if
// mat[i][j] is unique
function isUnique($mat, $i,
$j, $n, $m)
{
global $MAX;
// checking in row calculating
// sumrow will be moving column wise
$sumrow = 0;
for ($k = 0; $k < $m; $k++)
{
$sumrow += $mat[$i][$k];
if ($sumrow > 1)
return false;
}
// checking in column
// calculating sumcol
// will be moving row wise
$sumcol = 0;
for ($k = 0; $k < $n; $k++)
{
$sumcol += $mat[$k][$j];
if ($sumcol > 1)
return false;
}
return true;
}
function countUnique($mat, $n, $m)
{
$uniquecount = 0;
for ($i = 0; $i < $n; $i++)
for ($j = 0; $j < $m; $j++)
if ($mat[$i][$j] &&
2216
Chapter 325. Unique cells in a binary matrix
isUnique($mat, $i,
$j, $n, $m))
$uniquecount++;
return $uniquecount;
}
// Driver code
$mat = array(array(0, 1, 0, 0),
array(0, 0, 1, 0),
array(1, 0, 0, 1));
echo countUnique($mat, 3, 4);
// This code is contributed by ajit
?>
Output:
2217
Chapter 325. Unique cells in a binary matrix
colsum[j]++;
}
// Using above count arrays, find
// cells
int uniquecount = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (mat[i][j] &&
rowsum[i] > 1 &&
colsum[j] > 1)
uniquecount++;
return uniquecount;
}
// Driver code
int main()
{
int mat[][MAX] = {{0, 1, 0, 0},
{0, 0, 1, 0},
{1, 0, 0, 1}};
cout << countUnique(mat, 3, 4);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/unique-cells-binary-matrix/
2218
Chapter 326
We have discussed a problem to count the number of unique paths in a Grid when no
obstacle was present in the grid. But here the situation is quite different. While moving
through the grid, we can get some obstacles which we can not jump and that way to reach
the bottom right corner is blocked.
The most efficient solution to this problem can be achieved using dynamic programming.
Like every dynamic problem concept, we will not recompute the subproblems. A temporary
2D matrix will be constructed and value will be stored using the bottom up approach.
• Create a 2D matrix of same size of the given matrix to store the results.
• Traverse through the created array row wise and start filling the values in it.
• If an obstacle is found, set the value to 0.
• For the first row and column, set the value to 1 if obstacle is not found.
2219
Chapter 326. Unique paths in a Grid with Obstacles
• Set the sum of the right and the upper values if obstacle is not present at that corre-
sponding position in the given matirx
• Return the last value of the created 2d matrix
Output:
2220
Chapter 326. Unique paths in a Grid with Obstacles
Source
https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/
2221
Chapter 327
2222
Chapter 327. Validity of a given Tic-Tac-Toe board configuration
Basically, to find the validity of an input grid, we can think of the conditions when an input
grid is invalid. Let no. of “X”s be countX and no. of “O”s be countO. Since we know
that the game starts with X, a given grid of Tic-Tac-Toe game would be definitely invalid
if following two conditions meet
a) countX != countO AND
b) countX != countO + 1
Since “X” is always the first move, second condition is also required.
Now does it mean that all the remaining board positions are valid one? The answer is NO.
Think of the cases when input grid is such that both X and O are making straight lines.
This is also not valid position because the game ends when one player wins. So we need to
check the following condition as well
c) If input grid shows that both the players are in winning situation, it’s an invalid position.
d) If input grid shows that the player with O has put a straight-line (i.e. is in win condition)
and countX != countO, it’s an invalid position. The reason is that O plays his move only
after X plays his move. Since X has started the game, O would win when both X and O
has played equal no. of moves.
e) If input grid shows that X is in winning condition than xCount must be one greater that
oCount.
Armed with above conditions i.e. a), b), c) and d), we can now easily formulate an algo-
rithm/program to check the validity of a given Tic-Tac-Toe board position.
Another way to find the validity of a given board is using ‘inverse method’ i.e. rule out all
the possibilities when a given board is invalid.
2223
Chapter 327. Validity of a given Tic-Tac-Toe board configuration
C++
2224
Chapter 327. Validity of a given Tic-Tac-Toe board configuration
{
// Check if 'X' is also winner, then
// return false
if (isCWin(board, 'X'))
return false;
// Else return true xCount and yCount are same
return (xCount == oCount);
}
// If 'X' wins, then count of X must be greater
if (isCWin(board, 'X') && xCount != oCount + 1)
return false;
// If 'O' is not winner, then return true
return true;
}
return false;
}
// Driver program
int main()
{
char board[] = {'X', 'X', 'O',
'O', 'O', 'X',
'X', 'O', 'X'};
(isValid(board))? cout << "Given board is valid":
cout << "Given board is not valid";
return 0;
}
Python3
2225
Chapter 327. Validity of a given Tic-Tac-Toe board configuration
arr[matches[i][2]] == char):
return True
return False
def is_valid(arr):
# Count number of 'X' and 'O' in the given board
xcount = arr.count('X')
ocount = arr.count('O')
# Board can be valid only if either xcount and ocount
# is same or xount is one more than oCount
if(xcount == ocount+1 or xcount == ocount):
# Check if O wins
if win_check(arr, 'O'):
# Check if X wins, At a given point only one can win,
# if X also wins then return Invalid
if win_check(arr, 'X'):
return "Invalid"
# O can only win if xcount == ocount in case where whole
# board has values in each position.
if xcount == ocount:
return "Valid"
# If X wins then it should be xc == oc + 1,
# If not return Invalid
if win_check(arr, 'X') and xcount != ocount+1:
return "Invalid"
# if O is not the winner return Valid
if not win_check(arr, 'O'):
return "Valid"
# If nothing above matches return invalid
return "Invalid"
# Driver Code
arr = ['X', 'X', 'O',
'O', 'O', 'X',
'X', 'O', 'X']
print("Given board is " + is_valid(arr))
Output:
2226
Chapter 327. Validity of a given Tic-Tac-Toe board configuration
Source
https://www.geeksforgeeks.org/validity-of-a-given-tic-tac-toe-board-configuration/
2227
Chapter 328
Variance and
standard-deviation of a matrix
Input : 1 2 3
4 5 6
6 6 6
Output : variance: 3
deviation: 1
Input : 1 2 3
4 5 6
7 8 9
Output : variance: 6
deviation: 2
Explanation:
First mean should be calculated by adding sum of each elements of the matrix. After
calculating mean, it should be subtracted from each element of the matrix.Then square
each term and find out the variance by dividing sum with total elements.
Deviation: It is the square root of the variance.
Example:
2228
Chapter 328. Variance and standard-deviation of a matrix
1 2 3
4 5 6
7 8 9
2229
Chapter 328. Variance and standard-deviation of a matrix
Java
2230
Chapter 328. Variance and standard-deviation of a matrix
sum += a[i][j];
// Returning mean
return sum / (n * n);
}
// Function for
// calculating variance
static int variance(int a[][],
int n, int m)
{
int sum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// subtracting mean
// from elements
a[i][j] -= m;
// a[i][j] = fabs(a[i][j]);
// squaring each terms
a[i][j] *= a[i][j];
}
}
// taking sum
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum += a[i][j];
return sum / (n * n);
}
// Driver Code
public static void main (String[] args)
{
// declaring and
// initializing matrix
int mat[][] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
// for mean
int m = mean(mat, 3);
2231
Chapter 328. Variance and standard-deviation of a matrix
// for variance
int var = variance(mat, 3, m);
// for standard
// deviation
double dev = (int)Math.sqrt(var);
// displaying variance
// and deviation
System.out.println("Mean: " + m);
System.out.println("Variance: " +
var);
System.out.println("Deviation: " +
(int)dev);
}
}
// This code is contributed
// by akt_mit
C#
2232
Chapter 328. Variance and standard-deviation of a matrix
{
int sum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
// subtracting mean
// from elements
a[i, j] -= m;
// a[i][j] = fabs(a[i][j]);
// squaring each terms
a[i, j] *= a[i, j];
}
}
// taking sum
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
sum += a[i,j];
return sum / (n * n);
}
// Driver Code
static public void Main ()
{
// declaring and
// initializing matrix
int [,]mat = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
// for mean
int m = mean(mat, 3);
// for variance
int var = variance(mat, 3, m);
// for standard deviation
double dev = (int)Math.Sqrt(var);
// displaying variance and deviation
Console.WriteLine("Mean: " + m );
Console.WriteLine("Variance: " + var);
Console.WriteLine("Deviation: " + dev);
2233
Chapter 328. Variance and standard-deviation of a matrix
}
}
// This code is contributed by ajit
PHP
<?php
// PHP program to find mean
// and variance of a matrix.
// variance function declaration
// Function for calculating mean
function mean($a, $n)
{
// Calculating sum
$sum = 0;
for ($i = 0; $i < $n; $i++)
for ( $j = 0; $j < $n; $j++)
$sum += $a[$i][$j];
// Returning mean
return floor((int)$sum / ($n * $n));
}
// Function for calculating variance
function variance($a, $n, $m)
{
$sum = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n; $j++)
{
// subtracting mean
// from elements
$a[$i][$j] -= $m;
// a[i][j] = fabs(a[i][j]);
// squaring each terms
$a[$i][$j] *= $a[$i][$j];
}
}
// taking sum
for ($i = 0; $i < $n; $i++)
for ( $j = 0; $j < $n; $j++)
$sum += $a[$i][$j];
2234
Chapter 328. Variance and standard-deviation of a matrix
return floor((int)$sum / ($n * $n));
}
// Driver Code
// declaring and
// initializing matrix
$mat = array(array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9));
// for mean
$m = mean($mat, 3);
// for variance
$var = variance($mat, 3, $m);
// for standard deviation
$dev = sqrt($var);
// displaying variance
// and deviation
echo "Mean: " , $m , "\n",
"Variance: " , $var ,
"\n", "Deviation: " ,
floor($dev) , "\n";
// This code is contributed by ajit
?>
Output :
Mean: 5
Variance: 6
Deviation: 2
Improved By : jit_t
Source
https://www.geeksforgeeks.org/variance-standard-deviation-matrix/
2235
Chapter 329
Ways of filling matrix such that product of all rows and all columns are equal to unity -
GeeksforGeeks
Input : n = 2, m = 4, k = -1
Output : 8
Following configurations satisfy the conditions:-
Input : n = 2, m = 1, k = -1
Output : The number of filling the matrix
are 0
From the above conditions, it is clear that the only elements that can be entered in the
matrix are 1 and -1. Now we can easily deduce some of the corner cases
1. If k = -1, then the sum of number of rows and columns cannot be odd because -1 will
2236
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity
be present odd number of times in each row and column therefore if the sum is odd
then answer is .
2. If n = 1 or m = 1 then there is only one way of filling the matrix therefore answer is
1.
3. If none of the above cases are applicable then we fill the first rows and the
first columns with 1 and -1. Then the remaining numbers can be uniquely
identified since the product of each row an each column is already known therefore
the answer is .
C++
2237
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity
// If the above cases are not followed then we
// find ways to fill the n - 1 rows and m - 1
// columns which is 2 ^ ((m-1)*(n-1)).
return (modPower(modPower((long long)2, n - 1),
m - 1) % mod);
}
// Driver function for the program
int main()
{
int n = 2, m = 7, k = 1;
cout << countWays(n, m, k);
return 0;
}
Output:
64
Java
2238
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity
C#
2239
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity
2240
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity
PHP
<?php
// PHP program to find number
// of ways to fill a matrix under
// given constraints
$mod = 100000007;
// Returns a raised power t
// under modulo mod
function modPower($a, $t)
{
global $mod;
$now = $a; $ret = 1;
// Counting number of ways
// of filling the matrix
while ($t)
{
if ($t & 1)
$ret = $now * ($ret % $mod);
$now = $now * ($now % $mod);
$t >>= 1;
}
return $ret;
}
// Function calculating the answer
function countWays($n, $m, $k)
{
global $mod;
// if sum of numbers of rows
// and columns is odd i.e
// (n + m) % 2 == 1 and k = -1
// then there are 0 ways of
// filiing the matrix.
if ($k == -1 and ($n + $m) % 2 == 1)
return 0;
// If there is one row or
// one column then there
// is only one way of
// filling the matrix
if ($n == 1 or $m == 1)
2241
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity
return 1;
// If the above cases are
// not followed then we
// find ways to fill the
// n - 1 rows and m - 1
// columns which is
// 2 ^ ((m-1)*(n-1)).
return (modPower(modPower(2, $n - 1),
$m - 1) % $mod);
}
// Driver Code
$n = 2;
$m = 7;
$k = 1;
echo countWays($n, $m, $k);
// This code is contributed by anuj_67.
?>
Output:
64
Source
https://www.geeksforgeeks.org/ways-filling-matrix-product-rows-columns-equal-unity/
2242
Chapter 330
Source
https://www.geeksforgeeks.org/zigzag-or-diagonal-traversal-of-matrix/
2243
Chapter 331
heapq in Python to print all elements in sorted order from row and column wise sorted
matrix - GeeksforGeeks
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print
all elements of matrix in sorted order.
Examples:
This problem has existing solution please refer link. We will solve this problem in python
with the same approach of merging two sorted arrays using heapq module.
2244
Chapter 331. heapq in Python to print all elements in sorted order from row and column
wise sorted matrix
def sortedMatrix(mat):
# initialize result variable with first row of matrix
result=mat[0]
# now traverse through complete matrix
# after first row and merge each row with
# result one by one
# after last operation result will contain
# list of sorted elements of matrix
for row in mat[1:]:
result=list(merge(result,row))
return result
if __name__ == "__main__":
mat = [[10, 20, 30, 40],[15, 25, 35, 45], \
[27, 29, 37, 48],[32, 33, 39, 50]]
print 'Elements of matrix in sorted order'
print sortedMatrix(mat)
Output:
Source
https://www.geeksforgeeks.org/heapq-python-print-elements-sorted-order-row-column-wise-sorted-matrix/
2245