Sunteți pe pagina 1din 2245

Contents

1 A Boolean Matrix Question 22


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

2 A matrix probability question 44


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3 A square matrix as sum of symmetric and skew-symmetric matrices 52


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

4 Addition and Subtraction of Matrix using pthreads 60


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

5 Best meeting point in 2D binary array 66


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

6 Bisymmetric matrix 69
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

7 Boundary elements of a Matrix 76


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

8 C Program To Check whether Matrix is Skew Symmetric or not 86


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

9 C program for addition of two matrices 93


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

10 C program for subtraction of matrices 98


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

11 Center element of matrix equals sums of half diagonals 102


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

12 Centrosymmetric Matrix 109


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

13 Check for possible path in 2D matrix 115


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

1
Contents

14 Check given matrix is magic square or not 122


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

15 Check horizontal and vertical symmetry in binary matrix 130


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

16 Check if a Matrix is Invertible 138


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

17 Check if a given matrix is Hankel or not 150


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

18 Check if a given matrix is sparse or not 158


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

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

21 Check if given Sudoku board configuration is valid or not 170


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

22 Check if it is possible to make the given matrix increasing matrix or not174


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177

23 Check if possible to cross the matrix with given power 178


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

24 Check if possible to move from given coordinate to desired coordinate 186


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

25 Check if sums of i-th row and i-th column are same in matrix 193
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

26 Check if the given chessboard is valid or not 198


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

27 Check whether a given matrix is orthogonal or not 202


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

28 Check whether row or column swaps produce maximum size binary


sub-matrix with all 1s 217
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221

29 Cholesky Decomposition : Matrix Decomposition 222


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

2
Contents

30 Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral


way) 229
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

31 Collect maximum coins before hitting a dead end 232


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

32 Collect maximum points in a grid using two traversals 238


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

33 Common elements in all rows of a given matrix 242


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244

34 Construct Ancestor Matrix from a Given Binary Tree 245


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

35 Construct a linked list from 2D matrix 249


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

36 Construct a linked list from 2D matrix (Iterative Approach) 254


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258

37 Construct a unique matrix n x n for an input n 259


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266

38 Construct tree from ancestor matrix 267


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

39 Conway’s Game Of Life (Python Implementation) 272


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

40 Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix278


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290

41 Count all 0s which are blocked by 1s in binary matrix 291


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293

42 Count all possible paths from top left to bottom right of a mXn matrix 294
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

43 Count all sorted rows in a matrix 301


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307

44 Count elements smaller than or equal to x in a sorted matrix 308


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320

45 Count entries equal to x in a special matrix 321


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326

46 Count frequency of k in a matrix of size n where matrix(i, j) = i+j 327


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332

3
Contents

47 Count inversion pairs in a matrix 333


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

48 Count number of islands where every island is row-wise and column-wise


separated 338
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

49 Count number of squares in a rectangle 345


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350

50 Count number of ways to reach destination in a Maze 351


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360

51 Count of elements of an array present in every row of NxM matrix 361


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363

52 Count of number of given string in 2D character array 364


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

53 Count of possible hexagonal walks 368


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

54 Count pairs from two sorted matrices with given sum 375
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397

55 Count rows/columns with sum equals to diagonal sum 398


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405

56 Count sub-matrices having sum divisible ‘k’ 406


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

57 Count zeros in a row wise and column wise sorted matrix 419
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426

58 Counting sets of 1s and 0s in a binary matrix 427


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432

59 Counts paths from a point to reach Origin 433


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441

60 Create a matrix with alternating rectangles of O and X 442


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451

61 Determinant of a Matrix 452


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460

62 Diagonally Dominant Matrix 461


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467

63 Different Operations on Matrices 468


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470

4
Contents

64 Direction at last square block 471


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478

65 Discrete Cosine Transform (Algorithm and Program) 479


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483

66 Distance of nearest cell having 1 in a binary matrix 484


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494

67 Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication) 495


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498

68 Doolittle Algorithm : LU Decomposition 499


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504

69 Easy way to remember Strassen’s Matrix Equation 505


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

70 Efficiently compute sums of diagonals of a matrix 508


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516

71 Final cell position in the matrix 517


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520

72 Find Nth term (A matrix exponentiation example) 521


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524

73 Find Shortest distance from a guard in a Bank 525


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528

74 Find a common element in all rows of a given row-wise sorted matrix 529
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537

75 Find a peak element in a 2D array 538


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541

76 Find a specific pair in Matrix 542


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555

77 Find all permuted rows of a given row in a matrix 556


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560

78 Find all rectangles filled with 0 561


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564

79 Find difference between sums of two diagonals 565


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573

80 Find distinct elements common to all rows of a matrix 574


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580

5
Contents

81 Find duplicate rows in a binary matrix 581


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583

82 Find floor and ceil in an unsorted array 584


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590

83 Find if a 2-D array is completely traversed or not by following the cell


values 591
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594

84 Find if given matrix is Toeplitz or not 595


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604

85 Find if there is a rectangle in binary matrix with corners as 1 605


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608

86 Find length of the longest consecutive path from a given starting character609
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617

87 Find maximum element of each row in a matrix 618


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619

88 Find maximum length Snake sequence 620


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626

89 Find median in row wise sorted matrix 627


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632

90 Find number of endless points 633


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641

91 Find number of transformation to make two Matrix Equal 642


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648

92 Find orientation of a pattern in a matrix 649


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652

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

95 Find perimeter of shapes formed with 1s in binary matrix 664


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668

96 Find row number of a binary matrix having maximum number of 1s 669


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675

97 Find shortest safe route in a path with landmines 676


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681

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

100 Find the Surface area of a 3D figure 698


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706

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

104 Find the mean vector of a Matrix 721


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727

105 Find the number of islands | Set 1 (Using DFS) 728


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739

106 Find the row with maximum number of 1s 740


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747

107 Find trace of matrix formed by adding Row-major and Column-major


order of same matrix 748
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758

108 Find unique elements in a matrix 759


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 763

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

111 Flood fill Algorithm – how to implement fill() in paint? 780


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783

112 Form coils in a matrix 784


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792

113 Freivald’s Algorithm to check if a matrix is product of two 793


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803

114 Frequencies of even and odd numbers in a matrix 804

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

120 Gold Mine Problem 860


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866

121 Hilbert Matrix 867


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867

122 In-place convert matrix in specific order 868


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871

123 Inplace (Fixed space) M x N size matrix transpose | Updated 872


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 878

124 Inplace rotate square matrix by 90 degrees | Set 1 879


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891

125 Interchange elements of first and last rows in matrix 892


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895

126 Kronecker Product of two matrices 896


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904

127 Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix) 905


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907

128 Kth smallest element in a row-wise and column-wise sorted 2D array


| Set 1 908
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911

129 Largest area rectangular sub-matrix with equal number of 1’s and 0’s 912
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916

130 Largest connected component on a grid 917

8
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927

131 Largest rectangular sub-matrix having sum divisible by k 928


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932

132 Largest rectangular sub-matrix whose sum is 0 933


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 937

133 Largest sum Zigzag sequence in a matrix 938


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946

134 Latin Square 947


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952

135 Longest Increasing Path in Matrix 953


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956

136 Longest Possible Route in a Matrix with Hurdles 957


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961

137 Magic Square 962


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 972

138 Magic Square | Even Order 973


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981

139 Matrix Chain Multiplication | DP-8 982


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 993

140 Matrix Exponentiation 994


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1002

141 Matrix Multiplication | Recursive 1003


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1010

142 Matrix manipulation in Python 1011


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1014

143 Matrix sum except one item 1015


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1023

144 Maximize matrix as per given condition 1024


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1029

145 Maximize sum of N X N upper left sub-matrix from given 2N X 2N


matrix 1030
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1038

146 Maximize the binary matrix by filpping submatrix once 1039


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1041

9
Contents

147 Maximum XOR value in matrix 1042


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1049

148 Maximum and Minimum Values of an Algebraic Expression 1050


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1060

149 Maximum and Minimum in a square matrix. 1061


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1066

150 Maximum decimal value path in a binary matrix 1067


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1073

151 Maximum determinant of a matrix with every values either 0 or n 1074


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1079

152 Maximum difference of sum of elements in two rows in a matrix 1080


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1088

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

156 Maximum path sum in matrix 1103


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1109

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

160 Maximum product of 4 adjacent elements in matrix 1126


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1134

161 Maximum size rectangle binary sub-matrix with all 1s 1135


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1141

162 Maximum size square sub-matrix with all 1s 1142


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1148

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

166 Maximum sum of hour glass in matrix 1166


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1171

167 Maximum sum path in a matrix from top to bottom 1172


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1179

168 Maximum sum rectangle in a 2D matrix | DP-27 1180


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1186

169 Maximum value in a matrix which contain intersecting concentric sub-


matrix 1187
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1191

170 Maximum weight path ending at any element of last row in a matrix 1192
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1198

171 Mean and Median of a matrix 1199


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1204

172 Min Cost Path | DP-6 1205


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1217

173 Minimum Cost Path with Left, Right, Bottom and Up moves allowed 1218
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1221

174 Minimum Initial Points to Reach Destination 1222


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1227

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

178 Minimum cost to convert 3 X 3 matrix into magic square 1243

11
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1246

179 Minimum cost to sort a matrix of numbers from 0 to n^2 – 1 1247


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1254

180 Minimum difference between adjacent elements of array which contain


elements from each row of a matrix 1255
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1260

181 Minimum flip required to make Binary Matrix symmetric 1261


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1270

182 Minimum jumps to reach last building in a matrix 1271


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1279

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

185 Minimum product in a grid of adjacent elements 1294


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1298

186 Minimum queens required to cover all the squares of a chess board 1299
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1303

187 Minimum sum submatrix in a given 2D array 1304


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1307

188 Minimum time required to rot all oranges 1308


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1316

189 Mirror of matrix across diagonal 1317


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1323

190 Mobile Numeric Keypad Problem 1324


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1332

191 Move matrix elements in given direction and add elements with same
value 1333
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1356

192 Multiplication of Matrix using pthreads 1357


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1360

193 Multiplication of two Matrices in Single line using Numpy in Python 1361
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1363

194 N Queen in O(n) space 1364

12
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1367

195 N-th term of George Cantor set of rational numbers 1368


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1376

196 Nearest 1 in a binary matrix 1377


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1380

197 Number of cells a queen can move with obstacles on the chessborad 1381
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1389

198 Number of days until all chocolates become unhealthy 1390


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1396

199 Number of decisions to reach destination 1397


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1400

200 Number of elements greater than modified mean in matrix 1401


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1407

201 Number of pair of positions in matrix which are not accessible 1408
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1410

202 Number of palindromic paths in a matrix 1411


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1414

203 Number of paths with exactly k coins 1415


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1420

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

206 Pascal Matrix 1434


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1440

207 Path with maximum average value 1441


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1446

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

210 Possible moves of knight 1452

13
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1457

211 Prim’s Algorithm (Simple Implementation for Adjacency Matrix Rep-


resentation) 1458
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1460

212 Print K’th element in spiral form of matrix 1461


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1463

213 Print a given matrix in counter-clock wise spiral form 1464


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1475

214 Print a given matrix in reverse spiral form 1476


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1485

215 Print a given matrix in spiral form 1486


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1495

216 Print a given matrix in zigzag form 1496


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1503

217 Print a matrix in Reverse Wave Form 1504


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1512

218 Print a matrix in a spiral form starting from a point 1513


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1518

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

221 Print all n digit patterns formed by mobile Keypad 1528


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1531

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

224 Print cells with same rectangular sums in a matrix 1539


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1548

225 Print concentric rectangular pattern in a 2d matrix 1549


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1555

226 Print matrix in antispiral form 1556


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1561

14
Contents

227 Print matrix in diagonal pattern 1562


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1571

228 Print matrix in snake pattern 1572


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1578

229 Print matrix in zag-zag fashion 1579


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1592

230 Print maximum sum square sub-matrix of given size 1593


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1596

231 Print n x n spiral matrix using O(1) extra space 1597


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1604

232 Print shortest path to print a string on screen 1605


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1611

233 Print the corner elements and their sum in a 2-D matrix 1612
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1617

234 Print unique rows in a given boolean matrix 1618


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1622

235 Printing all solutions in N-Queen Problem 1623


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1627

236 Printing brackets in Matrix Chain Multiplication Problem 1628


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1632

237 Printing string in plus ‘+’ pattern in the matrix 1633


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1639

238 Program for Conway’s Game Of Life 1640


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1646

239 Program for Gauss-Jordan Elimination Method 1647


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1654

240 Program for Identity Matrix 1655


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1663

241 Program for Markov matrix 1664


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1669

242 Program for Rank of Matrix 1670


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1681

243 Program for Sudoku Generator 1682


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1687

15
Contents

244 Program for scalar multiplication of a matrix 1688


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1691

245 Program to Interchange Diagonals of Matrix 1692


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1696

246 Program to Print Matrix in Z form 1697


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1703

247 Program to check Involutory Matrix 1704


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1710

248 Program to check diagonal matrix and scalar matrix 1711


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1721

249 Program to check idempotent matrix 1722


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1727

250 Program to check if a matrix is symmetric 1728


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1737

251 Program to check if matrix is lower triangular 1738


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1742

252 Program to check if matrix is singular or not 1743


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1745

253 Program to check if matrix is upper triangular 1746


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1750

254 Program to check if two given matrices are identical 1751


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1756

255 Program to find Normal and Trace of a matrix 1757


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1762

256 Program to find all types of Matrix 1763


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1768

257 Program to find largest element in an array 1769


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1776

258 Program to find transpose of a matrix 1777


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1788

259 Program to multiply two matrices 1789


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1795

260 Program to print Lower triangular and Upper triangular matrix of an


array 1796
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1804

16
Contents

261 Program to print numbers in digital form 1805


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1823

262 Program to swap upper diagonal elements with lower diagonal elements
of matrix. 1824
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1829

263 Python Counter| Find duplicate rows in a binary matrix 1830


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1831

264 Python List Equality | Program to check if two given matrices are
identical 1832
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1833

265 Python heapq to find K’th smallest element in a 2D array 1834


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1835

266 Python map function to find row with maximum number of 1’s 1836
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1837

267 Python program to add two Matrices 1838


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1840

268 Python program to multiply two matrices 1841


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1843

269 Python | Print unique rows in a given boolean matrix using Set with
tuples 1844
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1845

270 Queries in a Matrix 1846


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1849

271 Queries on number of Binary sub-matrices of Given size 1850


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1858

272 Rat in a Maze with multiple steps or jump allowed 1859


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1863

273 Rat in a Maze | Backtracking-2 1864


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1872

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

277 Return previous element in an expanding matrix 1890


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1894

278 Reverse Diagonal elements of matrix 1895


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1899

279 Rotate Matrix Elements 1900


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1912

280 Rotate a Matrix by 180 degree 1913


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1925

281 Rotate a matrix by 90 degree in clockwise direction without using any


extra space 1926
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1931

282 Rotate a matrix by 90 degree without using any extra space | Set 2 1932
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1941

283 Rotate each ring of matrix anticlockwise by K elements 1942


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1946

284 Rotate the matrix right by K times 1947


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1955

285 Row wise sorting in 2D array 1956


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1959

286 Row-wise common elements in two diagonals of a square matrix 1960


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1964

287 Row-wise vs column-wise traversal of matrix 1965


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1967

288 Saddle point in a matrix 1968


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1974

289 Saddleback Search Algorithm in a 2D array 1975


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1979

290 Search a Word in a 2D Grid of characters 1980


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1983

291 Search element in a sorted matrix 1984


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1993

292 Search in a row wise and column wise sorted matrix 1994
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2001

293 Shift matrix elements row-wise by k 2002


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2008

18
Contents

294 Shortest distance between two cells in a matrix or grid 2009


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2012

295 Shortest path in a Binary Maze 2013


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2017

296 Solve the Crossword Puzzle 2018


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2023

297 Sort a Matrix in all way increasing order 2024


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2026

298 Sort the given matrix 2027


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2033

299 Sort the matrix row-wise and column-wise 2034


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2044

300 Sorting rows of matrix in ascending order followed by columns in de-


scending order 2045
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2051

301 Sparse Matrix Representations | Set 3 ( CSR ) 2052


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2056

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

304 Spiral Pattern 2070


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2075

305 Squares of Matrix Diagonal Elements 2076


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2088

306 Strassen’s Matrix Multiplication Algorithm | Implementation 2089


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2095

307 Submatrix Sum Queries 2096


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2103

308 Sudo Placement 2 | Matrix Series 2104


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2108

309 Sudo Placement[1.5] | Wolfish 2109


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2113

19
Contents

310 Sudoku | Backtracking-7 2114


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2121

311 Sum 2D array in Python using map() function 2122


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2123

312 Sum of Area of all possible square inside a rectangle 2124


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2128

313 Sum of both diagonals of a spiral odd-order square matrix 2129


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2133

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

316 Sum of middle row and column in Matrix 2155


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2160

317 Sum of upper triangle and lower triangle 2161


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2166

318 Summed Area Table – Submatrix Summation 2167


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2168

319 Swap major and minor diagonals of a square matrix 2169


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2174

320 System of Linear Equations in three variables using Cramer’s Rule 2175
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2179

321 The Celebrity Problem 2180


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2192

322 Total coverage of all zeros in a binary matrix 2193


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2200

323 Total number of decreasing paths in a matrix 2201


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2208

324 Turn an image by 90 degree 2209


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2213

325 Unique cells in a binary matrix 2214


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2218

326 Unique paths in a Grid with Obstacles 2219

20
Contents

Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2221

327 Validity of a given Tic-Tac-Toe board configuration 2222


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2227

328 Variance and standard-deviation of a matrix 2228


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2235

329 Ways of filling matrix such that product of all rows and all columns
are equal to unity 2236
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2242

330 Zigzag (or diagonal) traversal of Matrix 2243


Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2243

331 heapq in Python to print all elements in sorted order from row and
column wise sorted matrix 2244
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2245

21
Chapter 1

A Boolean Matrix Question

A Boolean Matrix Question - GeeksforGeeks


Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j]
is 1 (or true) then make all the cells of ith row and jth column as 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

Method 1 (Use two temporary arrays)


1) Create two temporary arrays row[M] and col[N]. Initialize all values of row[] and col[] as
0.
2) Traverse the input matrix mat[M][N]. If you see an entry mat[i][j] as true, then mark
row[i] and col[j] as true.
3) Traverse the input matrix mat[M][N] again. For each entry mat[i][j], check the values of
row[i] and col[j]. If any of the two values (row[i] or col[j]) is true, then mark mat[i][j] as true.
Thanks to Dixit Sethi for suggesting this method.

C++

// C++ Code For A Boolean Matrix Question


#include <bits/stdc++.h>
  
using namespace std;
#define R 3
#define C 4
  
void modifyMatrix(bool mat[R][C])
{
    bool row[R];
    bool col[C];
  
    int i, j;
      
    /* 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++)
        {
            if (mat[i][j] == 1)
            {
                row[i] = 1;
                col[j] = 1;

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

// Java Code For A Boolean Matrix Question


class GFG
{
    public static void modifyMatrix(int mat[ ][ ], int R, int C)
    {
        int row[ ]= new int [R];
        int col[ ]= new int [C];
        int i, j;
      
        /* 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++)
            {
                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++)
        {

25
Chapter 1. A Boolean Matrix Question

            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++)
            {
                System.out.print(mat[i][j]+ " ");
            }
            System.out.println();
        }
    }
      
    /* Driver program to test above functions */
    public static void main(String[] args) 
    {
        int mat[ ][ ] = { {1, 0, 0, 1},
                          {0, 0, 1, 0},
                          {0, 0, 0, 0},};
                      
                System.out.println("Matrix Intially");
                  
                printMatrix(mat, 3, 4);
              
                modifyMatrix(mat, 3, 4);
                System.out.println("Matrix after modification n");
                printMatrix(mat, 3, 4);
              
    } 
  
}
  
// This code is contributed by Kamal Rawal

Python3

# Python3 Code For A Boolean Matrix Question

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#

// C# Code For A Boolean


// Matrix Question
using System;
  
class GFG
{
    public static void modifyMatrix(int [,]mat, 
                                    int R, int C)
    {
        int []row = new int [R];
        int []col = new int [C];
        int i, j;
      
        /* 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++)
            {
                if (mat[i, j] == 1)
                {

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

Time Complexity: O(M*N)


Auxiliary Space: O(M + N)
Method 2 (A Space Optimized Version of Method 1)
This method is a space optimized version of above method 1. This method uses the first
row and first column of the input matrix in place of the auxiliary arrays row[] and col[] of
method 1. So what we do is: first take care of first row and column and store the info about
these two in two flag variables rowFlag and colFlag. Once we have this info, we can use
first row and first column as auxiliary arrays and apply method 1 for submatrix (matrix
excluding first row and first column) of size (M-1)*(N-1).
1) Scan the first row and set a variable rowFlag to indicate whether we need to set all 1s in
first row or not.
2) Scan the first column and set a variable colFlag to indicate whether we need to set all 1s
in first column or not.
3) Use first row and first column as the auxiliary arrays row[] and col[] respectively, consider
the matrix as submatrix starting from second row and second column and apply method 1.
4) Finally, using rowFlag and colFlag, update first row and first column if needed.
Time Complexity: O(M*N)
Auxiliary Space: O(1)
Thanks to Sidh for suggesting this method.

C++

#include <bits/stdc++.h>

32
Chapter 1. A Boolean Matrix Question

using namespace std;


#define R 3
#define C 4
  
void modifyMatrix(int mat[R][C])
{
    // variables to check if there are any 1
    // in first row and column
    bool row_flag = false;
    bool col_flag = false;
  
    // updating the first row and col if 1
    // is encountered
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; 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 < R; i++) {
        for (int 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 (int i = 0; i < C; i++) {
            mat[0][i] = 1;
        }
    }
  
    // modify first col if there was any 1

33
Chapter 1. A Boolean Matrix Question

    if (col_flag == true) {


        for (int i = 0; i < R; i++) {
            mat[i][0] = 1;
        }
    }
}
  
/* A utility function to print a 2D matrix */
void printMatrix(int mat[R][C])
{
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            cout << mat[i][j];
        }
        cout << "\n";
    }
}
  
// Driver function to test the above function
int main()
{
  
    int mat[R][C] = { { 1, 0, 0, 1 },
                      { 0, 0, 1, 0 },
                      { 0, 0, 0, 0 } };
  
    cout << "Input Matrix :\n";
    printMatrix(mat);
  
    modifyMatrix(mat);
  
    cout << "Matrix After Modification :\n";
    printMatrix(mat);
    return 0;
}
  
// This code is contributed by Nikita Tiwari

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

        for (int i = 0; i < mat.length; i ++){


            for (int j = 0; j < mat[0].length; j ++){
                System.out.print( mat[i][j] );
            }
                System.out.println("");
        }
    }
              
    // Driver function to test the above function
    public static void main(String args[] ){
                  
        int mat[][] = {{1, 0, 0, 1},
                {0, 0, 1, 0},
                {0, 0, 0, 0}};
                  
        System.out.println("Input Matrix :");
        printMatrix(mat);
              
        modifyMatrix(mat);
              
        System.out.println("Matrix After Modification :");
        printMatrix(mat);
              
    }
}
  
// This code is contributed by Arnav Kr. Mandal.

Python3

# Python3 Code For A Boolean Matrix Question


def modifyMatrix(mat) :
      
    # 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 in range(0, len(mat)) :
          
        for j in range(0, len(mat)) :
            if (i == 0 and mat[i][j] == 1) :
                row_flag = True
                      
            if (j == 0 and mat[i][j] == 1) :
                col_flag = True

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

// C# Code For A Boolean


// Matrix Question
using System;
  
class GFG

    public static void modifyMatrix(int[,] mat)
    {
                  
        // variables to check 
        // if there are any 1 
        // in first row and column
        bool row_flag = false;
        bool col_flag = false;
                  
        // updating the first
        // row and col if 1
        // is encountered
        for (int i = 0;
                 i < mat.GetLength(0); i++ )
        {
                for (int j = 0; 
                         j < mat.GetLength(1); 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.GetLength(0); i ++)
        {
                for (int j = 1; 
                         j < mat.GetLength(1); j ++)
                {

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

    // Driver Code


    public static void Main()
    {
        int[,] mat = {{1, 0, 0, 1},
                      {0, 0, 1, 0},
                      {0, 0, 0, 0}};
                  
        Console.Write("Input Matrix :\n");
        printMatrix(mat);
              
        modifyMatrix(mat);
              
        Console.Write("Matrix After " + 
                      "Modification :\n");
        printMatrix(mat);
    }
}
  
// This code is contributed
// by ChitraNayal

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

Improved By : jit_t, ChitraNayal, Abby_akku

42
Chapter 1. A Boolean Matrix Question

Source

https://www.geeksforgeeks.org/a-boolean-matrix-question/

43
Chapter 2

A matrix probability question

A matrix probability question - GeeksforGeeks


Given a rectangular matrix, we can move from current cell in 4 directions with equal proba-
bility. The 4 directions are right, left, top or bottom. Calculate the Probability that after N
moves from a given position (i, j) in the matrix, we will not cross boundaries of the matrix
at any point.
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to perform something similar to DFS. We recursively traverse in each of the 4
allowed direction and for each cell encountered, we calculate the required probability with
one less move. As each direction has equal probability, each direction will contribute to 1/4
of total probability of that cell i.e. 0.25. We return 0 if we step outside the matrix and
return 1 if N steps are completed without crossing matrix boundaries.
Below is the implementation of above idea :

C++

/// C++ program to find the probability 


// that we do not cross boundary of a 
// matrix after N moves.
#include <iostream>
using namespace std;
  
// check if (x, y) is valid matrix coordinate
bool isSafe(int x, int y, int m, int n)
{
    return (x >= 0 && x < m && 
            y >= 0 && y < n);
}
  

44
Chapter 2. A matrix probability question

// 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.
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;
}
  
// Driver code
int main()
{
    // matrix size
    int m = 5, n = 5;
  
    // coordinates of starting point
    int i = 1, j = 1;
  
    // Number of steps
    int N = 2;

45
Chapter 2. A matrix probability question

  
    cout << "Probability is "
        << findProbability(m, n, i, j, N);
  
    return 0;
}

Java

// Java program to find the probability


// that we do not cross boundary
// of a matrix after N moves.
import java.io.*;
  
class GFG {
      
// check if (x, y) is valid
// matrix coordinate
static boolean 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, 

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#

// C# program to find the probability


// that we do not cross boundary
// of a matrix after N moves.
using System;
  
class GFG 
{

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

    if (!isSafe($x, $y, $m, $n))


        return 0.0;
  
    // N steps taken
    if ($N == 0)
        return 1.0;
  
    // Initialize result
    $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;
}
  
// Driver code
  
// matrix size
$m = 5; $n = 5;
  
// coordinates of starting point
$i = 1; $j = 1;
  
// Number of steps
$N = 2;
  
echo "Probability is ", 
      findProbability($m, $n, $i, $j, $N);
  
// This code is contributed by nitin mittal. 
?>

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

A square matrix as sum of


symmetric and skew-symmetric
matrices

A square matrix as sum of symmetric and skew-symmetric matrices - GeeksforGeeks


Let A be a square matrix with all real number entries. Find two symmetric matrix P
and skew symmetric matrix Q such that P + Q = A.
Symmetric Matrix:- A square matrix is said to be symmetric matrix if the transpose of
the matrix is same as the original matrix.
Skew Symmetric Matrix:- A square matrix is said to be skew symmetric matrix if the
negative transpose of matrix is same as the original matrix.
Examples :

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

second matrix is Skew Symmetric as negative transpose


is same as this matrix. Also sum of the two matrices
is same as mat[][].

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

Let A be a square matrix, then


A = (1/2)*(A + A’) + (1/2)*(A – A’) Where A’ is the transpose matrix of A. In
the above formula (1/2)*(A + A’) represents symmetric matrix and (1/2)*(A – A’)
represents skew symmetric matrix. If we take a closer look, we can notice that the two
matrices are symmetric and skew symmetric (We are basically distributing half of two cell
values to both).

C++

// C++ program for distribute a square matrix into


// symmetric and skew symmetric matrix.
#include <bits/stdc++.h>
#define N 3
using namespace std;
  
/* Below functions can be used to verify result 
// Returns true if matrix is skew symmetric, 
// else false.
bool isSymmetric(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;
}
  
// Returns true if matrix is skew symmetric,

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

// Java program for distribute


// a square matrix into
// symmetric and skew symmetric
// matrix.
  
import java.io.*;
import java.util.*;
  
class GFG {
static void printMatrix(float mat[][])
{
    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++)
            System.out.print(mat[i][j] + "   ");
        System.out.println();
    }
}
   
static void printDistribution(float mat[][])
{
    // tr is the transpose of matrix mat.
    int N=mat.length;
    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];

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#

// C# program for distribute


// a square matrix into
// symmetric and skew 
// symmetric matrix.
using System;
  
class GFG 
{
  
static int N = 3;
static void printMatrix(float[,] mat)
{
    for (int i = 0; i < N; i++) 
    {
        for (int j = 0; j < N; j++)
            Console.Write(mat[i, j] + " ");
        System.Console.WriteLine();
    }

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

        for ($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;
        }
    }
  
    echo "Symmetric matrix-\n";
    printMatrix($symm);
  
    echo "Skew Symmetric matrix-\n";
    printMatrix($skewsymm);
}
  
// Driver Code
  
// mat is the N * N 
// square matrix.
$mat = array(array(2, -2, -4),
             array(-1, 3, 4),
             array(1, -2, -3));
printDistribution($mat);
  
// This code is contributed by mits.
?>

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

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/a-square-matrix-as-sum-of-symmetric-and-skew-symmetric-matrices/

59
Chapter 4

Addition and Subtraction of


Matrix using pthreads

Addition and Subtraction of Matrix using pthreads - GeeksforGeeks


Addition or Subtraction of matrices takes O(n^2) time without threads but using threads
we doesn’t reduce the time complexity of the program we divide the task into core like if we
have 4 core then divide the matrix into 4 part and each core take one part of matrix and
compute the operations and finally when each task is complete then all 4 thread join the
main program and show final output.
Note –This method only works when we have more then one CPU core if we have only one
core the Don’t create the thread because we divide the task and perform on only one CPU
so it is waste of time to dividing a tsk and then compute.

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 :

Sum of Matrix A and B:


9 12 8 8
10 9 9 9
6 8 9 16
2 5 12 11

61
Chapter 4. Addition and Subtraction of Matrix using pthreads

Subtraction of Matrix A and B:


-3 2 -2 4
8 -5 -9 -3
-6 -4 -7 -2
2 -1 2 7

Code – It is advised to execute the program in Linux based system.

#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

    int core = (int)arg;


  
    // Each thread computes 1/4th of matrix subtraction
    for (i = core * MAX / 4; i < (core + 1) * MAX / 4; i++) {
  
        for (j = 0; j < MAX; j++) {
  
            // Compute Subtract row wise
            sub[i][j] = mat_A[i][j] - mat_B[i][j];
        }
  
    }
  
}
  
  
// Driver Code
int main()
{
  
    int i, j, step = 0;
    // Generating random values in mat_A and mat_B
    for (i = 0; i < MAX; i++)  {
  
        for (j = 0; j < MAX; j++)  {
  
            mat_A[i][j] = rand() % 10;
            mat_B[i][j] = rand() % 10;
  
        }
  
    }
  
  
    // Displaying mat_A
    printf("\nMatrix A:\n");
  
    for (i = 0; i < MAX; i++) {
  
        for (j = 0; j < MAX; j++) {
  
            printf("%d ", mat_A[i][j]);
        }
  
        printf("\n");
    }
  
    // Displaying mat_B

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

Sum of Matrix A and B:

9 12 8 8
10 9 9 9
6 8 9 16
2 5 12 11

Subtraction of Matrix A and B:

-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

Best meeting point in 2D binary


array

Best meeting point in 2D binary array - GeeksforGeeks


You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in a
group. And the group of two or more people wants to meet and minimize the total travel
distance. They can meet anywhere means that there might be a home or not.

• 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:

Input : grid[][] = {{1, 0, 0, 0, 1},


{0, 0, 0, 0, 0},
{0, 0, 1, 0, 0}};
Output : 6
Best meeting point is (0, 2).
Total distance traveled is 2 + 2 + 2 = 6

Input : grid[3][5] = {{1, 0, 1, 0, 1},


{0, 1, 0, 0, 0},
{0, 1, 1, 0, 0}};
Output : 11

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.

/* C++ program to find best meeting point in 2D array*/


#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 5
  
int minTotalDistance(int grid[][COL]) {
    if (ROW == 0 || COL == 0) 
         return 0;
      
    vector<int> vertical;
    vector<int> horizontal;
      
    // Find all members home's position 
    for (int i = 0; i < ROW; i++) {
        for (int j = 0; j < COL; j++) {
            if (grid[i][j] == 1) {
                vertical.push_back(i);
                horizontal.push_back(j);
            }

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

Bisymmetric matrix - GeeksforGeeks


A Bisymmetric matrixis a square matrix that is symmetric about both of its main diagonals.
Given a matrix of size n x n. The task is to check if its is bisymmetric or not.
Examples :

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++

// CPP Program to check if a


// given matrix is Bisymmetric

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

// Java Program to check if a given matrix


// is Bisymmetric matrix
import java.io.*;
  
class GFG {
  
    static int MAX = 100;
      
    // Return if the given 
    // matrix is Bisymmetric matrix
    static boolean checkBisymmetric(int m[][], 
                        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
    public static void main (String[] args)
    {
        int n = 3;

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

# Python3 Program to check if a


# given matrix is Bisymmetric
# matrix
  
# Return if the given matrix
# is Bisymmetric matrix
def checkBisymmetric(m, n) :
      
    # Checking Across 
    # Forward Diagonal
    for i in range(0, n) :
        for j in range(0, i) : 
            # check if corresponding 
            # position element are equal.
            if (m[i][j] != m[j][i]) : 
                return false             
  
    # Backward Diagonal
    for i in range(0, n) : 
        # for each column, 
        # upto main diagonal
        for j in range(0, n - i) : 
              
            # check if corresponding 
            # position element are 
            # equal.
            if (m[i][j] != 
             m[n - j - 1][n - i - 1]) :
                return False
    return True;
  
# Driven Code

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#

// C# Program to check if a given matrix


// is Bisymmetric matrix
using System;
  
class GFG {
  
    //static int MAX = 100;
      
    // Return if the given 
    // matrix is Bisymmetric matrix
    static bool checkBisymmetric(int [,]m, 
                        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,

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

    // Backward Diagonal


    for ( $i = 0; $i < $n; $i++) 
  
        // for each column, 
        // upto main diagonal
        for ( $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
$n = 3;
$m = array(array( 1, 2, 3 ),
           array( 2, 5, 2 ),
           array( 3, 2, 1 ));
  
if(checkBisymmetric($m, $n))
echo "Yes" ; 
else
echo "No";
  
// This code is contributed by anuj_67.
?>

Output :

Yes

Improved By : vt_m, manishshaw1

Source

https://www.geeksforgeeks.org/bisymmetric-matrix/

75
Chapter 7

Boundary elements of a Matrix

Boundary elements of a Matrix - GeeksforGeeks


Printing Boundary Elements of a Matrix.
Examples:

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++

// C++ program to print boundary element of


// matrix.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
void printBoundary(int a[][MAX], int m, int n)
{
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {

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

// JAVA Code for 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)
                    System.out.print(a[i][j] + " ");
                else if (i == m-1)
                    System.out.print(a[i][j] + " ");
                else if (j == 0)
                    System.out.print(a[i][j] + " ");
                else if (j == n-1)
                    System.out.print(a[i][j] + " ");
                else
                    System.out.print("  ");
            }
            System.out.println("");
        }
    }

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

# Python program to print boundary element


# of matrix.
  
MAX = 100
   
def printBoundary(a, m, n):
    for i in range(m):
        for j in range(n):
            if (i == 0):
                print a[i][j],
            elif (i == m-1):
                print a[i][j],
            elif (j == 0):
                print a[i][j],
            elif (j == n-1):
                print a[i][j],
            else:
                print " ",
        print
          
# Driver code
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 Sachin Bisht

C#

// C# Code for Boundary 


// elements of a Matrix
using System;
  

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

function printBoundary($a, $m, $n)


{
    global $MAX;
    for ($i = 0; $i < $m; $i++) 
    {
        for ($j = 0; $j < $n; $j++) 
        {
            if ($i == 0)
                echo $a[$i][$j] , " ";
            else if ($i == $m - 1)
                echo $a[$i][$j] , " ";
            else if ($j == 0)
                echo $a[$i][$j] , " ";
            else if ($j == $n - 1)
                echo $a[$i][$j] , " ";
            else
                echo " " , " ";
        }
        echo "\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 ));
printBoundary($a, 4, 4);
      
// This code is contributed 
// by akt_mit
?>

Output:

1 2 3 4
5 8
1 4
5 6 7 8

Finding sum of boundary elements


Examples:

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++

// C++ program to find sum of boundary elements


// of matrix.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
int getBoundarySum(int a[][MAX], int m, int n)
{
    long long int 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 code
int main()
{
    int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, 
                    { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
    long long int sum = getBoundarySum(a, 4, 4);
    cout << "Sum of boundary elements is " << sum;
    return 0;
}

Java

// JAVA Code for Finding sum of boundary elements


class GFG {

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

# Python program to print boundary element 


# of matrix.
  
MAX = 100
   
def printBoundary(a, m, n):
    sum = 0
    for i in range(m):
        for j in range(n):
            if (i == 0):
                sum += a[i][j]
            elif (i == m-1):
                sum += a[i][j]

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#

// C# Code for Finding sum


// of boundary elements
using System;
  
class GFG
{
    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 Code
    static public void Main ()
    {
        int [,]a = {{ 1, 2, 3, 4 }, 
                    { 5, 6, 7, 8 }, 

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

// This code is contributed by ajit


?>

Output:

Sum of boundary elements is 54

Improved By : jit_t

Source

https://www.geeksforgeeks.org/boundary-elements-matrix/

85
Chapter 8

C Program To Check whether


Matrix is Skew Symmetric or
not

C Program To Check whether Matrix is Skew Symmetric or not - GeeksforGeeks


A Skew Symmetric Matrix or Anti-Symmetric Matrix is a square matrix whose transpose
is negative to that of the original matrix. If the entry in the ith row and jth column of a
matrix is a[i][j], i.e. if A = (a[i][j]) then the skew symmetric condition is -A = -a[j][i].
Examples :

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:

1. Find the transpose of the input matrix.


2. If the input matrix is equal to the negative of its transpose matrix, then the matrix is
Skew Symmetrical.

C++

86
Chapter 8. C Program To Check whether Matrix is Skew Symmetric or not

// C program to check whether given matrix


// is skew-symmetric or not
#include <stdio.h>
#include <stdlib.h>
  
#define ROW 3
#define COL 3
  
// Utility function to create transpose matrix
void transpose(int transpose_matrix[ROW][COL],
                         int matrix[ROW][COL])
{
   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
bool check(int transpose_matrix[ROW][COL],
                    int matrix[ROW][COL])
{
    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
void printMatrix(int matrix[ROW][COL])
{
    for (int i = 0; i < ROW; i++)
    {
       for (int j = 0; j < COL; j++)
            printf("%d ", matrix[i][j]);
       printf("\n");
    }
}
  
// Driver program to test above functions
int main()
{
    int matrix[ROW][COL] = {
                            {0, 5, -4},
                            {-5, 0, 1},
                            {4, -1, 0},
                           };

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

// java program to check


// whether given matrix
// is skew-symmetric or not
import java.io.*;
  
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 boolean 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;

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

# Python 3 program to check


# whether given matrix
# is skew-symmetric or not
ROW=3

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

C program for addition of two


matrices

C program for addition of two matrices - GeeksforGeeks


The below program adds two square matrices of size 4*4, we can change N for different
dimension.
C++

#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

// Java program for addition 


// of two matrices
  
class GFG
{
    static final int N = 4;
      
    // This function adds A[][] and B[][], and stores
    // the result in C[][]
    static void add(int A[][], int B[][], int C[][])
    {
        int i, j;
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                C[i][j] = A[i][j] + B[i][j];
    }
      
    // 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[][] = { {1, 1, 1, 1},
                        {2, 2, 2, 2},
                        {3, 3, 3, 3},
                        {4, 4, 4, 4}};

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

# Python3 program for addition 


# of two matrices
  
N = 4
   
# This function adds A[][]
# and B[][], and stores
# the result in C[][]
def add(A,B,C):
  
    for i in range(N):
        for j in range(N):
            C[i][j] = A[i][j] + B[i][j]
  
# driver code
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]]
   
C=A[:][:] # To store result
  
add(A, B, C)

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#

// C# program for addition 


// of two matrices
using System;
  
class GFG
{
    static int N = 4;
      
    // This function adds A[][] and B[][], and stores
    // the result in C[][]
    static void add(int[,] A, int [,]B, int [,]C)
    {
        int i, j;
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                C[i,j] = A[i,j] + B[i,j];
    }
      
    // 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 = { {1, 1, 1, 1},
                        {2, 2, 2, 2},
                        {3, 3, 3, 3},
                        {4, 4, 4, 4}};
      
        // To store result
        int [,]C = new int[N,N]; 
        int i, j;
        add(A, B, C);
      

96
Chapter 9. C program for addition of two matrices

    Console.WriteLine("Result matrix is ");


        for (i = 0; i < N; i++)
        {
            for (j = 0; j < N; j++)
            Console.Write(C[i,j] + " ");
            Console.WriteLine();
        }
    }
}
  
// This code is contributed by vt_m.

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.

How to pass a 2D array as a parameter in C?


The time complexity of the above program is O(n2 ).

Source

https://www.geeksforgeeks.org/c-program-addition-two-matrices/

97
Chapter 10

C program for subtraction of


matrices

C program for subtraction of matrices - GeeksforGeeks


The below program subtracts of two square matrices of size 4*4, we can change N for
different dimension.

#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

// Java program for subtraction of matrices


  
class GFG
{
     static final int N=4;
  
    // This function subtracts B[][] 
    // from A[][], and stores
    // the result in C[][]
    static void multiply(int A[][], int B[][], int C[][])
    {
        int i, j;
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                C[i][j] = A[i][j] - B[i][j];
    }
      
    // 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[][] = { {1, 1, 1, 1},
                        {2, 2, 2, 2},
                        {3, 3, 3, 3},

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

# program for subtraction of matrices


  
N = 4
   
# This function returns 1
# if A[][] and B[][] are identical
# otherwise returns 0
def multiply(A,B,C):
      
    for i in range(N):
        for j in range(N):
            C[i][j] = A[i][j] - B[i][j]  
  
#driver code
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]]
                      
C=A[:][:]         # To store result
      

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.

How to pass a 2D array as a parameter in C?


The time complexity of the above program is O(n2 ).

Source

https://www.geeksforgeeks.org/c-program-subtraction-matices/

101
Chapter 11

Center element of matrix equals


sums of half diagonals

Center element of matrix equals sums of half diagonals - GeeksforGeeks


Given a matrix of odd order i.e(5*5). Task is to check if the center element of the matrix is
equal to the individual sum of all the half diagonals.

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

Sum of Half Diagonal 3 = 11 + -2 = 9


Sum of Half Diagonal 4 = 5 + 4 = 9

Here, All the sums equal to the center element


that is mat[2][2] = 9

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++

// C++ Program to check if the center


// element is equal to the individual 
// sum of all the half diagonals
#include <stdio.h>
#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to Check center element 
// is equal to the individual 
// sum of all the half diagonals
bool HalfDiagonalSums(int mat[][MAX], int n)
{    
    // Find sums of half diagonals
    int diag1_left = 0, diag1_right = 0;
    int diag2_left = 0, diag2_right = 0;    
    for (int 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 && 

103
Chapter 11. Center element of matrix equals sums of half diagonals

            diag2_right == diag2_left &&


            diag1_right == diag2_left &&
            diag2_right == mat[n/2][n/2]);
}
  
// Driver code
int main()
{
    int a[][MAX] = { { 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} };
        cout << ( HalfDiagonalSums(a, 5) ? "Yes" : "No" );
    return 0;
}

Java

// Java program to find maximum elements 


// that can be made equal with k updates
import java.util.Arrays;
public class GFG {
      
    static int MAX = 100;
      
    // Function to Check center element 
    // is equal to the individual 
    // sum of all the half diagonals
    static boolean HalfDiagonalSums(int mat[][],
                                          int n)
    { 
          
        // Find sums of half diagonals
        int diag1_left = 0, diag1_right = 0;
        int diag2_left = 0, diag2_right = 0; 
        for (int 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];         
            }

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#

// C# program to find maximum 


// elements that can be made 
// equal with k updates
using System;
  
class GFG
{
  
    // Function to Check 
    // center element is
    // equal to the individual 
    // sum of all the half 
    // diagonals
    static bool HalfDiagonalSums(int [,]mat,
                                 int n)
    { 
          
        // Find sums of 
        // half diagonals
        int diag1_left = 0, 
            diag1_right = 0;

105
Chapter 11. Center element of matrix equals sums of half diagonals

        int diag2_left = 0, 


            diag2_right = 0; 
        for (int 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
    static public void Main ()
    {
        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}};
                      
        Console.WriteLine(HalfDiagonalSums(a, 5)? 
                                  "Yes" : "No" );
    }
}
  
// This code is contributed by ajit

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

Time Complexity : O(N)


Improved By : Sam007, jit_t

Source

https://www.geeksforgeeks.org/center-element-of-matrix-equals-sums-of-half-diagonals/

108
Chapter 12

Centrosymmetric Matrix

Centrosymmetric Matrix - GeeksforGeeks


Given a matrix of size n x n. The task is to check whether the given matrix is Centrosym-
metric Matrix or not.
In mathematics, a centrosymmetric matrix is a matrix which is symmetric about its center.

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

Below is the implemantation of the above approach:

CPP

// CPP Program to check whether given


// matrix is centrosymmetric or not.
#include <bits/stdc++.h>
using namespace std;
#define N 3
  
bool checkCentrosymmetricted(int n, int m[N][N])
{
    int 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 (int i = 0; i < mid_row; i++) {
  
        // If each element and its corresponding
        // element is not equal then return false.
        for (int j = 0; j < n; j++) {
            if (m[i][j] != m[n - i - 1][n - j - 1])
                return false;
        }
    }
  
    return true;
}
  
// Driven Program
int main()
{
    int n = 3;
    int m[N][N] = { { 1, 3, 5 },
                    { 6, 8, 6 },
                    { 5, 3, 1 } };
  
    (checkCentrosymmetricted(n, m) ? 
              (cout << "Yes") : (cout << "No"));
  
    return 0;
}

110
Chapter 12. Centrosymmetric Matrix

Java

// Java Program to check whether given


// matrix is centrosymmetric or not.
import java.io.*;
  
class GFG {
          
    static int N = 3;
      
    static boolean checkCentrosymmetricted(
                           int n, int m[][])
    {
        int mid_row;
      
        // Finding the middle row of the
        // matrix
        if ((n & 1)>0)
            mid_row = n / 2 + 1;
        else
            mid_row = n / 2;
      
        // for each row upto middle row.
        for (int i = 0; i < mid_row; i++)
        {
      
            // If each element and its 
            // corresponding element is
            // not equal then return false.
            for (int j = 0; j < n; j++)
            {
                if (m[i][j] !=
                  m[n - i - 1][n - j - 1])
                    return false;
            }
        }
      
        return true;
    }
      
    // Driven Program
    public static void main (String[] args)
    {
        int n = 3;
        int m[][] = { { 1, 3, 5 },
                      { 6, 8, 6 },
                      { 5, 3, 1 } };
  

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#

// C# Program to check whether given


// matrix is centrosymmetric or not.
using System;
  
class GFG {
          
    ///static int N = 3;
      
    static bool checkCentrosymmetricted(
                        int n, int [,]m)
    {
        int mid_row;
      
        // Finding the middle row of the
        // matrix
        if ((n & 1)>0)
            mid_row = n / 2 + 1;
        else
            mid_row = n / 2;
      
        // for each row upto middle row.
        for (int i = 0; i < mid_row; i++)
        {
      
            // If each element and its 
            // corresponding element is
            // not equal then return false.
            for (int j = 0; j < n; j++)
            {
                if (m[i,j] !=
                m[n - i - 1,n - j - 1])
                    return false;
            }
        }
      
        return true;
    }

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

Check for possible path in 2D


matrix

Check for possible path in 2D matrix - GeeksforGeeks


Given a 2D array(m x n), check if there is any path from top left to bottom right. In the
matrix, -1 is considered as blockage (can’t go through this cell) and 0 is considered path cell
(can go through it).
Examples:

Input : arr[][] = {{ 0, 0, 0, -1, 0},


{-1, 0, 0, -1, -1},
{ 0, 0, 0, -1, 0},
{-1, 0, 0, 0, 0},
{ 0, 0, -1, 0, 0}}
Output : Yes

Input : arr[][] = {{ 0, 0, 0, -1, 0},


{-1, 0, 0, -1, -1},
{ 0, 0, 0, -1, 0},
{-1, 0, -1, 0, 0},
{ 0, 0, -1, 0, 0}}
Output : No

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++

// CPP program to find if there is path 


// from top left to right bottom
#include <iostream>
using namespace std;
  
#define row 5
#define col 5
  
// to find the path from
// top left to bottom right
bool isPath(int arr[row][col])
{
    // set arr[0][0] = 1
    arr[0][0] = 1;
  
    // Mark reachable (from top left) nodes 
    // in first row and first column.
    for (int i = 1; i < row; i++) 
        if (arr[0][i] != -1)
            arr[0][i] = arr[0][i - 1];   
  
    for (int j = 1; j < col; j++) 
        if (arr[j][0] != -1)
            arr[j][0] = arr[j - 1][0];    
  
    // Mark reachable nodes in remaining
    // matrix.
    for (int i = 1; i < row; i++) 
        for (int 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
int main()
{
    // Given array

116
Chapter 13. Check for possible path in 2D matrix

    int arr[row][col] = { { 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))
      cout << "Yes";
    else
      cout << "No";
  
return 0;
}

Java

// Java program to find if there is path


// from top left to right bottom
class GFG
{
    // to find the path from
    // top left to bottom right
    static boolean isPath(int arr[][])
    {
        // set arr[0][0] = 1
        arr[0][0] = 1;
  
        // Mark reachable (from top left) nodes
        // in first row and first column.
        for (int i = 1; i < 5; i++)
            if (arr[0][i] != -1)
                arr[0][i] = arr[0][i - 1];
        for (int j = 1; j < 5; j++)
            if (arr[j][0] != -1)
                arr[j][0] = arr[j - 1][0];
  
        // Mark reachable nodes in
        //  remaining matrix.
        for (int i = 1; i < 5; i++)
            for (int j = 1; j < 5; j++)
                if (arr[i][j] != -1)
                    arr[i][j] = Math.max(arr[i][j - 1],
                                        arr[i - 1][j]);
  
        // return yes if right 
        // bottom index is 1
        return (arr[5 - 1][5 - 1] == 1);

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#

// C# program to find if there is path


// from top left to right bottom
using System;
  
class GFG
{
    // to find the path from
    // top left to bottom right
    static bool isPath(int [,]arr)
    {
        // set arr[0][0] = 1
        arr[0, 0] = 1;
  
        // Mark reachable (from top left) nodes
        // in first row and first column.
        for (int i = 1; i < 5; i++)
            if (arr[0, i] != -1)
                arr[0, i] = arr[0, i - 1];
        for (int j = 1; j < 5; j++)
            if (arr[j,0] != -1)
                arr[j,0] = arr[j - 1, 0];
  
        // Mark reachable nodes in

118
Chapter 13. Check for possible path in 2D matrix

        // remaining matrix.


        for (int i = 1; i < 5; i++)
            for (int j = 1; j < 5; j++)
                if (arr[i, j] != -1)
                    arr[i, j] = Math.Max(arr[i, j - 1],
                                        arr[i - 1, j]);
  
        // return yes if right 
        // bottom index is 1
        return (arr[5 - 1, 5 - 1] == 1);
    }
      
    //Driver code 
    public static void Main()
    {
        // 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))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed 
// by vt_m

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

Time Complexity is O(n^2).


Improved By : vt_m

Source

https://www.geeksforgeeks.org/check-possible-path-2d-matrix/

121
Chapter 14

Check given matrix is magic


square or not

Check given matrix is magic square or not - GeeksforGeeks


Given a matrix, check whether it’s Magic Square or not. A Magic Square is a n x n matrix
of distinct element from 1 to n2 where sum of any row, column or diagonal is always equal
to same number.
Examples:

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.

1. Find sum of prime diagonal.


2. calculate sum of each rows and columns.

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++

// C++ program to check whether a given 


// matrix is magic matrix or not
#include <bits/stdc++.h>
  
#define N 3
using namespace std;
  
// Returns true if mat[][] is magic
// square, else returns false.
bool isMagicSquare(int mat[][N])

    // calculate the sum of 
    // the prime diagonal
    int sum = 0; 
    for (int i = 0; i < N; i++)
        sum = sum + mat[i][i];
  
    // For sums of Rows 
    for (int i = 0; i < N; i++) {
          
        int rowSum = 0;     
        for (int 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;
    }
  
    // For sums of Columns
    for (int i = 0; i < N; i++) {
          
        int colSum = 0;     
        for (int j = 0; j < N; j++)
            colSum += mat[j][i];
  
        // check if every column sum is 
        // equal to prime diagonal sum
        if (sum != colSum) 

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

// JAVA program to check whether a given


// matrix is magic matrix or not
  
import java.io.*;
  
class GFG {
      
    static int N = 3;
      
    // Returns true if mat[][] is magic
    // square, else returns false.
    static boolean isMagicSquare(int mat[][])
    {
          
        // calculate the sum of
        // the prime diagonal
        int sum = 0;
        for (int i = 0; i < N; i++)
            sum = sum + mat[i][i];
  
        // For sums of Rows
        for (int i = 0; i < N; i++) {
  
            int rowSum = 0;

124
Chapter 14. Check given matrix is magic square or not

            for (int 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;
        }
  
        // For sums of Columns
        for (int i = 0; i < N; i++) {
  
            int colSum = 0;
            for (int 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 program to
    // test above function
    public static void main(String[] args)
    {
        int mat[][] = {{ 2, 7, 6 },
                       { 9, 5, 1 },
                       { 4, 3, 8 }};
  
        if (isMagicSquare(mat))
            System.out.println("Magic Square");
        else
            System.out.println("Not a magic" +
                                    " Square");
    }
}
  
// This code is contributed by vt_m

Python3

# Python3 program to check whether a given 


# matrix is magic matrix or not
N = 3

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

// C# program to check whether a given


// matrix is magic matrix or not
using System;
  
class GFG 
{
      
    static int N = 3;
      
    // Returns true if mat[][] is magic
    // square, else returns false.
    static bool isMagicSquare(int[,] mat)
    {
          
        // calculate the sum of
        // the prime diagonal
        int sum = 0;
        for (int i = 0; i < N; i++)
            sum = sum + mat[i, i];
  
        // For sums of Rows
        for (int i = 0; i < N; i++) {
  
            int rowSum = 0;
            for (int 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;
        }
  
        // For sums of Columns
        for (int i = 0; i < N; i++) 
        {
  
            int colSum = 0;
            for (int 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;

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

Improved By : KRV, nitin mittal

Source

https://www.geeksforgeeks.org/check-given-matrix-is-magic-square-or-not/

129
Chapter 15

Check horizontal and vertical


symmetry in binary matrix

Check horizontal and vertical symmetry in binary matrix - GeeksforGeeks


Given a 2D binary matrix of N rows and M columns. The task is to check whether the ma-
trix is horizontal symmetric, vertical symmetric or both. The matrix is said to be horizontal
symmetric if the first row is same as the last row, the second row is same as the second
last row and so on. And the matrix is said to be vertical symmetric if the first column is
same as the last column, the second column is same as the second last column and so on.
Print “VERTICAL” if the matrix is vertical symmetric, “HORIZONTAL” if the matrix is
vertical symmetric, “BOTH” if the matrix is vertical and horizontal symmetric and “NO” if
not symmetric.
Examples :

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++

// C++ program to find if a matrix is symmetric.


#include <bits/stdc++.h>
#define MAX 1000
using namespace std;
  
void checkHV(int arr[][MAX], int N, int M)
{
    // Initializing as both horizontal and vertical
    // symmetric.
    bool 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 (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
            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 (int i=0, k=M-1; i<M/2; i++, k--)

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

// Java program to find if


// a matrix is symmetric.
import java.io.*;
  
public class GFG {
      
static void checkHV(int [][]arr, int N,
                    int M)
{
      
    // Initializing as both horizontal 
    // and vertical symmetric.

132
Chapter 15. Check horizontal and vertical symmetry in binary matrix

    boolean horizontal = true;


    boolean 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
            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 (int i = 0, k = M - 1;
             i < M / 2; i++, k--)
    {
          
        // 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)
        System.out.println("NO");
          
    else if (horizontal && !vertical)
        System.out.println("HORIZONTAL");
          

133
Chapter 15. Check horizontal and vertical symmetry in binary matrix

    else if (vertical && !horizontal)


        System.out.println("VERTICAL");
          
    else
        System.out.println("BOTH");
}
  
    // Driver Code
    static public void main (String[] args)
    {
        int [][]mat = { {1, 0, 1},
                        {0, 0, 0},
                        {1, 0, 1}};
  
            checkHV(mat, 3, 3);
    }
}
  
// This code is contributed by vt_m.

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

            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 (int i = 0, k = M - 1;
             i < M / 2; i++, k--)
    {
          
        // 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)
        Console.WriteLine("NO");
          
    else if (horizontal && ! vertical)
        Console.WriteLine("HORIZONTAL");
          
    else if (vertical && ! horizontal)
        Console.WriteLine("VERTICAL");
          
    else
        Console.WriteLine("BOTH");
}
  
    // Driver Code
    static public void Main ()
    {
        int [,]mat = { {1, 0, 1},
                        {0, 0, 0},
                        {1, 0, 1}};
  
        checkHV(mat, 3, 3);

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

            // check if every cell is identical


            if ($arr[$i][$j] != $arr[$k][$j])
            {
                $horizontal = false;
                break;
            }
        }
    }
  
    if (!$horizontal && !$vertical)
        echo "NO\n";
    else if ($horizontal && !$vertical)
        cout << "HORIZONTAL\n";
    else if ($vertical && !$horizontal)
        echo "VERTICAL\n";
    else echo "BOTH\n";
}
  
// Driver Code
$mat = array(array (1, 0, 1),
             array (0, 0, 0),
             array (1, 0, 1));
checkHV($mat, 3, 3);
  
// This code is contributed by nitin mittal. 
?>

Output :

BOTH

Time Complexity: O(N*M).


Improved By : vt_m, nitin mittal

Source

https://www.geeksforgeeks.org/check-horizontal-vertical-symmetry-binary-matrix/

137
Chapter 16

Check if a Matrix is Invertible

Check if a Matrix is Invertible - GeeksforGeeks


In linear algebra, an n-by-n square matrix A is called Invertible, if there exists an n-by-n
square matrix B such that

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++

// C++ program to find Deteminant of a matrix


#include <bits/stdc++.h>
using namespace std;
  
// Dimension of input square matrix
#define N 4
  
// Function to get cofactor of mat[p][q] in temp[][]. n is current
// dimension of mat[][]
void getCofactor(int mat[N][N], int temp[N][N], 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.

139
Chapter 16. Check if a Matrix is Invertible

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;
}
  
bool isInvertible(int mat[N][N], int n)
{
    if (determinantOfMatrix(mat, N) != 0)
        return true;
    else
        return false;
}
  
// 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 } };
    if (isInvertible(mat, N))
        cout << "Yes";
    else

140
Chapter 16. Check if a Matrix is Invertible

        cout << "No";


    return 0;
}

Java

// Java program to find


// Determinant of a matrix
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++;
                }
            }
        }
    }
    }
  

141
Chapter 16. Check if a Matrix is Invertible

    /* 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
  
    // 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;
    }
  
    static boolean isInvertible(int [][]mat, int n)
    {
        if (determinantOfMatrix(mat, N) != 0)
            return true;
        else
            return false;
    }
  
    // Driver Code
    public static void main(String []args)
    {
        int [][]mat = {{1, 0, 2, -1 },

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

# Function to get cofactor of 


# mat[p][q] in temp[][]. n is 
# current dimension of mat[][]
def getCofactor(mat, temp, p, q, n):
    i = 0
    j = 0
  
    # Looping for each element
    # of the matrix
    for row in range(n): 
          
        for col in range(n):
              
            # Copying into temporary matrix
            # only those element which are 
            # not in given row and column
            if (row != p and col != q) :
                  
                temp[i][j] = mat[row][col]
                j += 1
  
                # Row is filled, so increase 
                # row index and reset col index
                if (j == n - 1):
                    j = 0
                    i += 1
  
# Recursive function for 
# finding determinant of matrix.
# n is current dimension of mat[][]. 
def determinantOfMatrix(mat, n):
    D = 0 # Initialize result
  

143
Chapter 16. Check if a Matrix is Invertible

    # Base case : if matrix 


    # contains single element
    if (n == 1):
        return mat[0][0]
          
    # To store cofactors
    temp = [[0 for x in range(N)] 
               for y in range(N)] 
  
    sign = 1 # To store sign multiplier
  
    # Iterate for each 
    # element of first row
    for f in range(n):
          
        # 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
  
def isInvertible(mat, n):
    if (determinantOfMatrix(mat, N) != 0):
        return True
    else:
        return False
      
# Driver Code
mat = [[ 1, 0, 2, -1 ],
       [ 3, 0, 0, 5 ],
       [ 2, 1, 4, -3 ],
       [ 1, 0, 5, 0 ]];
      
N = 4
if (isInvertible(mat, N)):
    print("Yes")
else:
    print("No")
  
# This code is contributed
# by ChitraNayal

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

static int determinantOfMatrix(int[,] 


                               mat, int n)
{
int D = 0; // Initialize result
  
// Base case : if matrix 
// contains single element
if (n == 1)
    return mat[0, 0];
      
// To store cofactors
int[,] temp = new int[N, N]; 
  
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;
}
  
static bool isInvertible(int[,] mat, int n)
{
    if (determinantOfMatrix(mat, N) != 0)
        return true;
    else
        return false;
}
  
// Driver Code
public static void Main() 
{
    int[,] mat = {{ 1, 0, 2, -1 },
                  { 3, 0, 0, 5 },
                  { 2, 1, 4, -3 },
                  { 1, 0, 5, 0 }};
    if (isInvertible(mat, N))
        Console.Write("Yes");

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

Check if a given matrix is


Hankel or not

Check if a given matrix is Hankel or not - GeeksforGeeks


Given a matrix m[][] of size n x n. The task is to check whether given matrix is Hankel
Matrix or not.
In linear algebra, a Hankel matrix (or catalecticant matrix), named after Hermann Hankel,
is a square matrix in which each ascending skew-diagonal from left to right is constant.
Examples:

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

Observe, for a matrix to be Hankel Matrix, it must be of the form,

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++

// C++ Program to check if given matrix is


// Hankel Matrix or not.
#include <bits/stdc++.h>
using namespace std;
#define N 4
  
// Function to check if given matrix is Hankel
// Matrix or not.
bool checkHankelMatrix(int n, int m[N][N])
{
    // for each row
    for (int i = 0; i < n; i++) {
  
        // for each column
        for (int 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;
            }
        }
    }

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

// Java Program to check if given matrix is


// Hankel Matrix or not.
import java.io.*;
import java.util.*;
  
class GFG {
  
    // Function to check if given matrix 
    // is Hankel Matrix or not.
    static boolean checkHankelMatrix(int n,
                                 int m[][])
    {
        // for each row
        for (int i = 0; i < n; i++) {
      
            // for each column
            for (int 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

152
Chapter 17. Check if a given matrix is Hankel or not

                    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;
                }
            }
        }
      
        return true;
    }
      
    // Drivers code
    public static void main(String args[])
    {
        int n = 4;
        int m[][] = {
            { 1, 2, 3, 5 },
            { 2, 3, 5, 8 },
            { 3, 5, 8, 0 },
            { 5, 8, 0, 9 }
        };
      
        if(checkHankelMatrix(n, m)) 
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Anuj_67.

Python 3

# Python 3 Program to check if given matrix is


# Hankel Matrix or not.
  
N = 4
  
# Function to check if given matrix is Hankel
# Matrix or not.

153
Chapter 17. Check if a given matrix is Hankel or not

def checkHankelMatrix(n, m):


  
    # for each row
    for i in range( 0, n):
  
        # for each column
        for j in range( 0, n): 
  
            # 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
              
    return True
  
# Drivers code
n = 4
m =[[1, 2, 3, 5,],
    [2, 3, 5, 8,],
    [3, 5, 8, 0,],
    [5, 8, 0, 9]] 
(print("Yes") if checkHankelMatrix(n, m)
                      else print("No"))
  
# This code is contributed by Smitha.

C#

// C# Program to check if given matrix is


// Hankel Matrix or not.
using System;
  
class GFG {
  

154
Chapter 17. Check if a given matrix is Hankel or not

    // Function to check if given matrix 


    // is Hankel Matrix or not.
    static bool checkHankelMatrix(int n,
                                int [,]m)
    {
        // for each row
        for (int i = 0; i < n; i++) {
      
            // for each column
            for (int 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;
                }
            }
        }
      
        return true;
    }
      
    // Drivers code
    public static void Main()
    {
        int n = 4;
        int [,]m = {
            { 1, 2, 3, 5 },
            { 2, 3, 5, 8 },
            { 3, 5, 8, 0 },
            { 5, 8, 0, 9 }
        };

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

Check if a given matrix is


sparse or not

Check if a given matrix is sparse or not - GeeksforGeeks


A matrix is a two dimensional data objects having m rows and n columns, therefore a total
of m*n values. If most of the values of a matrix is 0 then we say that the matrix is sparse.
Consider a definition of Sparse where a matrix is considered sparse if number of 0s is more
than half of the elements in matrix,
Examples:

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

// CPP code to check if a matrix is


// sparse.

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

// Java code to check 


// if a matrix is
// sparse.
  
import java.io.*;
  
class GFG {
      
    static int MAX = 100;
       
    static boolean isSparse(int array[][], int m, int n)
    {
        int counter = 0;

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

# Python 3 code to check


# if a matrix is
# sparse.
  
MAX = 100
   
def isSparse(array,m, n) :
      
    counter = 0
   
    # Count number of zeros
    # in the matrix
    for i in range(0,m) :
        for j in range(0,n) :
            if (array[i][j] == 0) :
                counter = counter + 1
   

160
Chapter 18. Check if a given matrix is sparse or not

    return (counter > 


            ((m * n) // 2))
  
# Driver Function
array = [ [ 1, 0, 3 ],
          [ 0, 0, 4 ],
          [ 6, 0, 0 ] ]
m = 3
n = 3
  
if (isSparse(array, m, n)) :
    print("Yes")
else :
    print("No")
      
      
# this code is contributed by
# Nikita tiwari

C#

// C# code to check if a matrix is


// sparse.
using System;
  
class GFG {
      
    static bool isSparse(int [,]array, 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
    public static void Main()
    {
        int [,]array = { { 1, 0, 3 }, 
                         { 0, 0, 4 }, 
                         { 6, 0, 0 } };
      

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

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++

// C++ program to check if we can make a


// grid of character sorted using adjacent
// swaps.
#include <bits/stdc++.h>
using namespace std;
  
// v[] is vector of strings. len is length
// of strings in every row.
bool check(vector<string> v, int len)
{
    int n = v.size();
    for (int i = 0; i < n; i++) 
        sort(v[i].begin(), v[i].end());
      
    for (int i = 0; i < len-1; i++) 
        for (int j = 0; j < n; j++) 
            if (v[i][j] > v[i+1][j])
                return false;
    return true;
}
  
// Driver code
int main()
{
    vector<string> v = { "ebcda", "ihgfj", "klmno", 
                               "pqrst", "yvwxu" };
    int len = 5; // Length of strings
    check(v, len)? cout << "Yes" : cout << "No";
    return 0;
}

Python

# Python program to check if we can make a


# grid of character sorted using adjacent
# swaps.
  
# v[] is vector of strings. len is length
# of strings in every row.
def check(v, l):

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

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

The idea is based on below article.


A Program to check if strings are rotations of each other or not
Steps :

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

Below is C++ implementation of above steps.

// C++ program to check if all rows of a matrix


// are rotations of each other
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
  
// Returns true if all rows of mat[0..n-1][0..n-1]
// are rotations of each other.
bool isPermutedMatrix( int mat[MAX][MAX], int n)
{
    // Creating a string that contains elements of first
    // row.
    string str_cat = "";
    for (int i = 0 ; i < n ; i++)
        str_cat = str_cat + "-" + to_string(mat[0][i]);
  
    // Concatenating the string with itself so that
    // substring search operations can be performed on
    // this
    str_cat = str_cat + str_cat;
  
    // Start traversing remaining rows
    for (int i=1; i<n; i++)
    {
        // Store the matrix into vector in the form
        // of strings
        string curr_str = "";
        for (int j = 0 ; j < n ; j++)
            curr_str = curr_str + "-" + to_string(mat[i][j]);
  
        // Check if the current string is present in
        // the concatenated string or not
        if (str_cat.find(curr_str) == string::npos)
            return false;
    }
  
    return true;
}
  
// Drivers code
int main()
{
    int n = 4 ;
    int mat[MAX][MAX] = {{1, 2, 3, 4},
        {4, 1, 2, 3},
        {3, 4, 1, 2},

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

Check if given Sudoku board


configuration is valid or not

Check if given Sudoku board configuration is valid or not - GeeksforGeeks


Given a Sudoku Board configuration, check whether it is valid or not.
Examples:

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

Below is the C++ code.

// Program to check whether given sudoku 


// board is valid or not
#include <bits/stdc++.h>
using namespace std;
  
// Checks whether there is any duplicate 
// in current row or not
bool notInRow(char arr[][9], int row)
{
    // Set to store characters seen so far.
    set<char> st;
  
    for (int i = 0; i < 9; i++) {
  
        // If already encountered before, return false
        if (st.find(arr[row][i]) != st.end())
            return false;
  
        // If it is not an empty cell, insert value
        // at the current cell in the set
        if (arr[row][i] != '.')
            st.insert(arr[row][i]);
    }
    return true;
}
  
// Checks whether there is any duplicate
// in current column or not.
bool notInCol(char arr[][9], int col)
{
    set<char> st;
  
    for (int i = 0; i < 9; i++) {
  
        // If already encountered before, return false
        if (st.find(arr[i][col]) != st.end())
            return false;
  
        // If it is not an empty cell,
        // insert value at the current cell in the set
        if (arr[i][col] != '.')
            st.insert(arr[i][col]);
    }
    return true;
}
  

171
Chapter 21. Check if given Sudoku board configuration is valid or not

// Checks whether there is any duplicate


// in current 3x3 box or not.
bool notInBox(char arr[][9], int startRow, int startCol)
{
    set<char> st;
  
    for (int row = 0; row < 3; row++) {
        for (int col = 0; col < 3; col++) {
            char curr = arr[row + startRow][col + startCol];
  
            // If already encountered before, return false
            if (st.find(curr) != st.end())
                return false;
  
            // If it is not an empty cell,
            // insert value at current cell in set
            if (curr != '.')
                st.insert(curr);
        }
    }
    return true;
}
  
// Checks whether current row and current column and
// current 3x3 box is valid or not
bool isValid(char arr[][9], int row, int col)
{
    return notInRow(arr, row) && notInCol(arr, col) &&
           notInBox(arr, row - row % 3, col - col % 3);
}
  
bool isValidConfig(char arr[][9], int n)
{
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
  
            // If current row or current column or
            // current 3x3 box is not valid, return false
            if (!isValid(arr, i, j))
                return false;
        }
    }
    return true;
}
  
// Drivers code
int main()
{

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

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:-

• For each row, the elements are in the increasing order.


• For each column, the elements are in the increasing order.

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.

Note: There can be more than one solution for a matrix.


Approach: Let dp[i][j] denote the element at row i and column j of matrix dp. Since the
matrix is non-decreasing, the following two conditions should be held:

• dp[i][j] >= dp[i][j-1], in row i elements are non-decreasing.


• dp[i][j] >= dp[i-1][j], in column j elements are non-decreasing.

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.

// CPP program to Check if we can make


// the given matrix increasing matrix or not
#include <bits/stdc++.h>
using namespace std;
#define n 4
#define m 4
  
// Function to find increasing matrix
void findIncreasingMatrix(int dp[n + 1][m + 1])
{
    bool flag = false;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
  
            // Putting max into b as per the above approach
            int b = max(dp[i - 1][j], dp[i][j - 1]);
  
            // If b is -1 than putting 1 to it
            b = max(1, b);
  
            // If dp[i][j] has to be filled with max
            if (dp[i][j] == -1)

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

Check if possible to cross the


matrix with given power

Check if possible to cross the matrix with given power - GeeksforGeeks


Given a matrix of N X M, each cell consist of an integer. We have initial power of K
and we are allowed to move right, down or diagonal. When we move to any cell, we absorb
mat[i][j] value and loose that much amount from your power. If our power became less than
0 at any time, we cannot move further from that point. Now, our task is to find if there
is any path from (1, 1) to (n, m) that we can cover with power k. If possible, output the
maximum value we can absorb, else if there is no path print “-1”.
Examples :

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

The idea is to use Dynamic Programming to solve the problem.


Approach :

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.

• We can write the recurrence dp[ i ][ j ][ k ] = true if either

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]]

i.e the three possible moves we could have.


• We have base case dp[0][0][0] be true.
• The answer is -2 if dp[n-1][m-1][k] is false for all k between 0 and k+1.
• Otherwise, the answer is the maximum k such that dp[n-1][m-1][k] is true.

Below is C++ implementation of this approach :


CPP

// CPP program to find if it is possible to cross


// the matrix with given power
#include <bits/stdc++.h>
#define N 105
#define R 3
#define C 4
using namespace std;
  
int maximumValue(int n, int m, int p, int grid[R][C])
{
    bool dp[N][N][N];
  
    // Initializing array dp with false value.
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < N; k++)
                dp[i][j][k] = false;
        }
    }
  
    // For each value of dp[i][j][k]
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            for (int k = grid[i][j]; k <= p; k++) {
  
                // For first cell and for each value of k
                if (i == 0 && j == 0) {

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

// Java program to find if it 


// is possible to cross the matrix
// with given power
class GFG
{
      
static final int N = 105;
static final int R = 3;
static final int C = 4;
  
static int maximumValue(int n, int m, int p,
                                int grid[][])
{
    boolean dp[][][] = new boolean[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;
                }
  

181
Chapter 23. Check if possible to cross the matrix with given power

                // 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]]);
                }
            }
        }
    }
    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 (String[] args)
{
    int n = 3, m = 4, p = 9;
    int grid[][] = {{ 2, 3, 4, 1 },
                    { 6, 5, 5, 3 },

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

Time Complexity: O(n3 )

Source

https://www.geeksforgeeks.org/check-possible-cross-matrix-given-power/

185
Chapter 24

Check if possible to move from


given coordinate to desired
coordinate

Check if possible to move from given coordinate to desired coordinate - GeeksforGeeks


Given two coordinates (x, y) and (a, b). Find if it is possible to reach (x, y) from (a, b).
Only possible moves from any coordinate (i, j) are

• (i-j, j)
• (i, i-j)
• (i+j, j)
• (i, i+j)

Given x, y, a, b can be negative.


Examples:

Input : (x, y) = (1, 1) and (a, b) = (2, 3).


Output : Yes.
(1, 1) -> (2, 1) -> (2, 3).

Input : (x, y) = (2, 1) and (a, b) = (2, 3).


Output : Yes.

Input : (x, y) = (35, 15) and (a, b) = (20, 25).


Output : Yes.
(35, 15) -> (20, 15) -> (5, 15) -> (5, 10) -> (5, 5) ->
(10, 5) -> (15, 5) -> (20, 5) -> (20, 25)

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++

// C++ program to check if it is possible to reach


// (a, b) from (x, y).
#include <bits/stdc++.h>
using namespace std;
  
// Returns GCD of i and j
int gcd(int i, int 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)
bool ispossible(int x, int y, int a, int 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));
}
  
// Driven Program
int main()
{
    // Converting coordinate into positive integer
    int x = 35, y = 15;
    int a = 20, b = 25;
    (ispossible(x, y, a, b)) ? (cout << "Yes") : (cout << "No");
    return 0;
}

187
Chapter 24. Check if possible to move from given coordinate to desired coordinate

Java

// Java program to check if it is possible


// to reach (a, b) from (x, y).
class GFG {
  
    // Returns GCD of i and j
    static int gcd(int i, int 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)
    static boolean 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(String[] args)
    {
  
        // Converting coordinate into positive integer
        int x = 35, y = 15;
        int a = 20, b = 25;
        if (ispossible(x, y, a, b))
            System.out.print("Yes");
        else
            System.out.print("No");
    }
}
// This code is contributed by Anant Agarwal.

188
Chapter 24. Check if possible to move from given coordinate to desired coordinate

Python

# Python program to check if it is possible to reach


# (a, b) from (x, y).
# Returns GCD of i and j
def 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)
def ispossible(x, y, a, b):
    # Find absolute values of all as sign doesn't
    # matter.
    x, y, a, b = abs(x), abs(y), abs(a), abs(b)
   
    # If gcd is equal then it is possible to reach.
    # Else not possible.
    return (gcd(x, y) == gcd(a, b))
   
# Driven Program
    # Converting coordinate into positive integer
x, y = 35, 15
a, b = 20, 25
if(ispossible(x, y, a, b)):
    print "Yes"
else:
    print "No"
# Contributed by Afzal Ansari

C#

// C# program to check if it is possible


// to reach (a, b) from (x, y).
using System;
  
class GFG {
  
    // Returns GCD of i and j
    static int gcd(int i, int j)
    {
        if (i == j)
            return i;

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

Improved By : nitin mittal

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

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

Expected time complexity is O(m x n) where m is number of rows and n is number of


columns.
The idea is really simple. We use a nested loop to calculate sum of each row and column
and then check whether their sum is equal or not.
The C++ implementation of the above idea is given below.

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

// Function to check the if sum of a row


// is same as corresponding column
bool areSumSame(int a[][MAX], int n, int m)
{
    int sum1 = 0, sum2 = 0;
    for (int i = 0; i < n; i++) {
        sum1 = 0, sum2 = 0;
        for (int j = 0; j < m; j++) {
            sum1 += a[i][j];
            sum2 += a[j][i];
        }
        if (sum1 == sum2)
            return true;
    }
    return false;
}
  
// Driver Code
int main()
{
    int n = 4; // number of rows
    int m = 4; // number of columns
    int M[n][MAX] = { { 1, 2, 3, 4 },
                      { 9, 5, 3, 1 }, 
                      { 0, 3, 5, 6 },
                      { 0, 4, 5, 6 } };
    cout << areSumSame(M, n, m) << "n";
    return 0;
}

Java

// java program to check if there are two


// adjacent set bits.
public class GFG {
      
    // Function to check the if sum of a row
    // is same as corresponding column
    static boolean areSumSame(int a[][], 
                             int n, int m)
    {
        int sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++) 
        {
            sum1 = 0;
            sum2 = 0;
            for (int j = 0; j < m; j++)
            {

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

# Python program to check the if


# sum of a row is same as 
# corresponding column
MAX = 100;
  
# Function to check the if sum 
# of a row is same as
# corresponding column
def areSumSame(a, n, m):
    sum1 = 0
    sum2 = 0
    for i in range(0, n):
        sum1 = 0
        sum2 = 0

195
Chapter 25. Check if sums of i-th row and i-th column are same in matrix

        for j in range(0, m):


            sum1 += a[i][j]
            sum2 += a[j][i]
          
        if (sum1 == sum2):
            return 1
      
    return 0
  
# Driver Code
n = 4; # number of rows
m = 4; # number of columns
M = [ [ 1, 2, 3, 4 ],
      [ 9, 5, 3, 1 ],
      [ 0, 3, 5, 6 ],
      [ 0, 4, 5, 6 ] ]
        
print(areSumSame(M, n, m))
  
# This code is contributed by Sam007.

C#

// C# program to check if there are two


// adjacent set bits.
using System;
  
class GFG {
      
    // Function to check the if sum of a row
    // is same as corresponding column
    static bool areSumSame(int [,]a, int n, int m)
    {
        int sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++) 
        {
            sum1 = 0;
            sum2 = 0;
            for (int j = 0; j < m; j++)
            {
                sum1 += a[i,j];
                sum2 += a[j,i];
            }
              
            if (sum1 == sum2)
                return true;
        }
          

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

Check if the given chessboard is


valid or not

Check if the given chessboard is valid or not - GeeksforGeeks


Given a NXN chessboard. The task is to check if the given chessboard is valid or not. A
chess board is considered valid if every 2 adjacent cells are painted with different color. Two
cells are considered adjacent if they share a boundary.

First chessboard is valid whereas second is invalid.


Examples:

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:

int X[] = {0, -1, 0, 1};


int Y[] = {1, 0, -1, 0};

bool validateConfiguration(int M[N][N])


{
bool isValid = true;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
for (int k = 0; k < 4; k++)
{
int newX = i + X[k];
int newY = j + Y[k];
if (newX < N && newY = 0 &&
newY >= 0 && M[newX][newY] == M[i][j])
{
isValid = false;
}
}
}
}
return isValid;
}

Below is the implemantation of this approach:

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

    // Traversing each cell of the chess board.


    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
  
            // for each adjacent cells
            for (int k = 0; k < 4; k++) {
                int newX = i + X[k];
                int newY = j + Y[k];
  
                // checking if they have different color
                if (newX < n && newY < n && newX >= 0 && 
                    newY >= 0 && c[newX][newY] == c[i][j]) {
                    isValid = false;
                }
            }
        }
    }
    return isValid;
}
  
// Driven Program
int main()
{
    int n = 2;
    int c[2][2] = { { 1, 0 },
                    { 0, 1 } };
  
    (isValid(c, n)) ? (cout << "Yes") : (cout << "No");
    return 0;
}

Python 3

# Python 3 Program to Check 


# if the given chessboard
# is valid or not
MAX = 2
  
# Check if the given chess
# board is valid or not.
def isValid(c, n) :
  
    X = [ 0, -1, 0, 1]
    Y = [ 1, 0, -1, 0]
    isValid = True
  
    # Traversing each cell 
    # of the chess board. 

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

Check whether a given matrix is


orthogonal or not

Check whether a given matrix is orthogonal or not - GeeksforGeeks


We are given a matrix, we need to check whether it is an orthogonal matrix or not. An
orthogonal matrix is a square matrix and satisfies the following condition:

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

// C++ code to check whether


// a matrix is orthogonal or not
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 100
  
bool isOrthogonal(int a[][MAX], 
                  int m, int n) 
{
if (m != n)
    return false;
  
// Find transpose
int trans[n][n];
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
    trans[i][j] = a[j][i];
  
// Find product of a[][] 
// and its transpose
int prod[n][n];
for (int i = 0; i < n; i++) 
{
    for (int j = 0; j < n; j++) 
    {
  
    int sum = 0;
    for (int 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 (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)

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

// Java code to check whether


// a matrix is orthogonal or not
import java .io.*;
class GFG {
      
    //static int MAX =100;
    static boolean isOrthogonal(int [][]a, 
                                int m, 
                                int n) 
    {
        if (m != n)
            return false;
          
        // Find transpose
        int [][]trans = new int[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                trans[i][j] = a[j][i];
          
        // Find product of a[][] 
        // and its transpose
        int [][]prod = new int[n][n];
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 

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

# Python code to check 

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#

// C# code to check whether


// a matrix is orthogonal or not
using System;
  
class GFG
{
      
    //static int MAX =100;
    static bool isOrthogonal(int [,]a, 
                             int m, 
                             int n) 
    {
        if (m != n)
            return false;
          
        // Find transpose
        int [,]trans = new int[n, n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                trans[i, j] = a[j, i];
          
        // Find product of a[][] 
        // and its transpose
        int [,]prod = new int[n, n];
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
          
                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]);

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++

// C++ code to check whether


// a matrix is orthogonal or not
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 100
  
bool isOrthogonal(int a[][MAX], 
                  int m, int n) 
{
if (m != n)
    return false;
  
// Multiply A*A^t
for (int i = 0; i < n; i++) 
{
    for (int j = 0; j < n; j++) 
    {
  
    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]);
    }
  

210
Chapter 27. Check whether a given matrix is orthogonal or not

    if (i == j && sum != 1)


        return false;
    if (i != j && sum != 0)
        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

// C# code to check whether


// a matrix is orthogonal or not
using System;
  
class GFG
{
    //static int MAX =100;
  
    static bool isOrthogonal(int[,]a, 
                             int m, 
                             int n) 
    {
        if (m != n)
            return false;
          
        // Multiply A*A^t
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < n; j++)
            {
          
            int sum = 0;

211
Chapter 27. Check whether a given matrix is orthogonal or not

            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

Python3

# Python code to check 


# whether a matrix is 
# orthogonal or not
  
def isOrthogonal(a, m, n) :
    if (m != n) :
        return False
      
    # Multiply A*A^t
    for i in range(0, n) :

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#

// C# code to check whether


// a matrix is orthogonal or not
using System;
  
public class GFG
{
    //static int MAX =100;
  
    static bool isOrthogonal(int[,]a, int m, int n) 
    {
        if (m != n)
            return false;
          
        // Multiply A*A^t
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

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

Improved By : KRV, vt_m, jit_t, manishshaw1

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

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:

// C++ program to find maximum binary sub-matrix


// with row swaps and column swaps.
#include <bits/stdc++.h>
#define R 5
#define C 3
using namespace std;
  
// Precompute the number of consecutive 1 below the
// (i, j) in j-th column and the number of consecutive 1s
// on right side of (i, j) in i-th row.
void precompute(int mat[R][C], int ryt[][C + 2],
                               int dwn[R + 2][C + 2])
{
    // Travesing the 2d matrix from top-right.
    for (int j=C-1; j>=0; j--)
    {
        for (int i=0; i<R; ++i)
        {
            // If (i,j) contain 0, do nothing
            if (mat[i][j] == 0)
                ryt[i][j] = 0;
  
            // Counting consecutive 1 on right side

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

    int b[C] = { 0 }, ans = 0;


  
    for (int i = 0; i < R; ++i)
    {
        // Copying the row.
        for (int j = 0; j < C; ++j)
            b[j] = dwn[i][j];
  
        // Sort the copied array
        sort(b, b + C);
  
        // Find maximum submatrix size.
        for (int i = 0; i < C; ++i)
            ans = max(ans, b[i] * (C - i));
    }
  
    return ans;
}
  
void findMax1s(int mat[R][C])
{
    int ryt[R + 2][C + 2], dwn[R + 2][C + 2];
    memset(ryt, 0, sizeof ryt);
    memset(dwn, 0, sizeof dwn);
  
    precompute(mat, ryt, dwn);
  
    // Solving for row swap and column swap
    int rswap = solveRowSwap(ryt);
    int cswap = solveColumnSwap(dwn);
  
    // Comparing both.
    (rswap > cswap)? (cout << "Row Swap\n" << rswap << endl):
                     (cout << "Column Swap\n" << cswap << endl);
}
  
// Driven Program
int main()
{
    int mat[R][C] = {{ 0, 0, 0 },
                     { 1, 1, 0 },
                     { 1, 1, 0 },
                     { 0, 0, 0 },
                     { 1, 1, 0 }};
  
    findMax1s(mat);
    return 0;
}

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

Cholesky Decomposition : Matrix Decomposition - GeeksforGeeks


In linear algebra, a matrix decomposition or matrix factorization is a factorization of
a matrix into a product of matrices. There are many different matrix decompositions. One
of them is Cholesky Decomposition.
The Cholesky decomposition or Cholesky factorization is a decomposition of a Hermi-
tian, positive-definite matrix into the product of a lower triangular matrix and its conjugate
transpose. The Cholesky decomposition is roughly twice as efficient as the LU decomposition
for solving systems of linear equations.
The Cholesky decomposition of a Hermitian positive-definite matrix A is a decomposition of
the form A = [L][L]T , where L is a lower triangular matrix with real and positive diagonal
entries, and LT denotes the conjugate transpose of L. Every Hermitian positive-definite
matrix (and thus also every real-valued symmetric positive-definite matrix) has a unique
Cholesky 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 :

Below is the implementation of Cholesky Decomposition.

C++

// CPP program to decompose a matrix using


// Cholesky Decomposition
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  

223
Chapter 29. Cholesky Decomposition : Matrix Decomposition

void Cholesky_Decomposition(int matrix[][MAX], 


                                      int n)
{
    int lower[n][n];
    memset(lower, 0, sizeof(lower));
  
    // Decomposing a matrix into Lower Triangular
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            int sum = 0;
  
            if (j == i) // summation for diagnols
            {
                for (int 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 (int k = 0; k < j; k++)
                    sum += (lower[i][k] * lower[j][k]);
                lower[i][j] = (matrix[i][j] - sum) /
                                      lower[j][j];
            }
        }
    }
  
    // Displaying Lower Triangular and its Transpose
    cout << setw(6) << " Lower Triangular"  
         << setw(30) << "Transpose" << endl;
    for (int i = 0; i < n; i++) {
          
        // Lower Triangular
        for (int j = 0; j < n; j++)
            cout << setw(6) << lower[i][j] << "\t";
        cout << "\t";
          
        // Transpose of Lower Triangular
        for (int j = 0; j < n; j++)
            cout << setw(6) << lower[j][i] << "\t";
        cout << endl;
    }
}
  
// Driver Code
int main()
{

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

static void Cholesky_Decomposition(int[,] matrix,


                                   int n)
{
    int[,] lower = new int[n, n];
  
    // Decomposing a matrix 
    // into Lower Triangular
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            int sum = 0;
  
            // summation for diagnols
            if (j == i) 
            {
                for (int k = 0; k < j; k++)
                    sum += (int)Math.Pow(lower[j, k], 2);
                lower[j, j] = (int)Math.Sqrt(matrix[j, j] -
                                                      sum);
            } 
              
            else
            {
  
                // Evaluating L(i, j) 
                // using L(j, j)
                for (int k = 0; k < j; k++)
                    sum += (lower[i, k] * 
                            lower[j, k]);
                lower[i, j] = (matrix[i,j] - sum) /
                                       lower[j, j];
            }
        }
    }
  
    // Displaying Lower 
    // Triangular and its Transpose
    Console.WriteLine("  Lower Triangular\t   Transpose");
    for (int i = 0; i < n; i++) 
    {
          
        // Lower Triangular
        for (int j = 0; j < n; j++)
            Console.Write(lower[i, j] + "\t");
        Console.Write("");
          
        // Transpose of 

227
Chapter 29. Cholesky Decomposition : Matrix Decomposition

        // Lower Triangular


        for (int j = 0; j < n; j++)
            Console.Write(lower[j, i] + "\t");
        Console.WriteLine();
    }
}
  
// Driver Code
static int Main()
{
    int n = 3;
    int[,] matrix = {{4, 12, -16},
                     {12, 37, -43},
                     {-16, -43, 98}};
                       
    Cholesky_Decomposition(matrix, n);
    return 0;
}
}
  
// This code is contributed by mits

Output:

Lower Triangular Transpose


2 0 0 2 6 -8
6 1 0 0 1 5
-8 5 3 0 0 3

Improved By : Mithun Kumar

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)

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.

// C++ program to fill a matrix with values from


// 1 to n*n in spiral fashion.
#include <bits/stdc++.h>
using namespace std;

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

Time complexity: O(m * n)

Source

https://www.geeksforgeeks.org/circular-matrix-construct-a-matrix-with-numbers-1-to-mn-in-spiral-way/

231
Chapter 31

Collect maximum coins before


hitting a dead end

Collect maximum coins before hitting a dead end - GeeksforGeeks


Given a character matrix where every cell has one of the following values.

'C' --> This cell has coin

'#' --> This cell is a blocking cell.


We can not go anywhere from this.

'E' --> This cell is empty. We don't get


a coin, but we can move from here.

Initial position is cell (0, 0) and initial direction is right.


Following are rules for movements across cells.
If face is Right, then we can move to below cells
Move one step ahead, i.e., cell (i, j+1) and direction remains right.
Move one step down and face left, i.e., cell (i+1, j) and direction becomes left.
If face is Left, then we can move to below cells

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:

maxCoins(i, j, d): Maximum number of coins that can be


collected if we begin at cell (i, j)
and direction d.
d can be either 0 (left) or 1 (right)

// If this is a blocking cell, return 0. isValid() checks


// if i and j are valid row and column indexes.
If (arr[i][j] == '#' or isValid(i, j) == false)
return 0

// 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

return result + max(maxCoins(i+1, j, 1), // Down


maxCoins(i, j+1, 0)); // Ahead in right

Below is C++ implementation of above recursive algorithm.

// A Naive Recursive C++ program to find maximum number of coins


// that can be collected before hitting a dead end
#include<bits/stdc++.h>
using namespace std;
#define R 5
#define C 5
  
// to check whether current cell is out of the grid or not
bool isValid(int i, int j)
{
    return (i >=0 && i < R && j >=0 && j < C);
}
  
// dir = 0 for left, dir = 1 for facing right.  This function returns
// number of maximum coins that can be collected starting from (i, j).
int maxCoinsRec(char arr[R][C],  int i, int j, int dir)
{
    // If this is a invalid cell or if cell is a blocking cell
    if (isValid(i,j) == false || arr[i][j] == '#')
        return 0;
  
    // Check if this cell contains the coin 'C' or if its empty 'E'.
    int result = (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
       return result + max(maxCoinsRec(arr, i+1, j, 0),     // Down
                             maxCoinsRec(arr, i, j+1, 1));  // Ahead in right
  
    // Direction is left
    // Get the maximum of two cases when you are facing left in this cell
     return  result + max(maxCoinsRec(arr, i+1, j, 1),    // Down
                           maxCoinsRec(arr, i, j-1, 0));  // Ahead in left
}
  
// 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'}

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:

Maximum number of collected coins is 8

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.

// A Dynamic Programming based C++ program to find maximum


// number of coins that can be collected before hitting a
// dead end
#include<bits/stdc++.h>
using namespace std;
#define R 5
#define C 5
  
// to check whether current cell is out of the grid or not
bool isValid(int i, int j)
{
    return (i >=0 && i < R && j >=0 && j < C);
}
  
// dir = 0 for left, dir = 1 for right.  This function returns
// number of maximum coins that can be collected starting from
// (i, j).
int maxCoinsUtil(char arr[R][C],  int i, int j, int dir,
                 int dp[R][C][2])
{
    // If this is a invalid cell or if cell is a blocking cell
    if (isValid(i,j) == false || arr[i][j] == '#')
        return 0;
  
    // If this subproblem is already solved than return the
    // already evaluated answer.
    if (dp[i][j][dir] != -1)
       return dp[i][j][dir];

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:

Maximum number of collected coins is 8

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

Collect maximum points in a


grid using two traversals

Collect maximum points in a grid using two traversals - GeeksforGeeks


Given a matrix where every cell represents points. How to collect maximum points using
two traversals under following conditions?
Let the dimensions of given grid be R x C.
1) The first traversal starts from top left corner, i.e., (0, 0) and should reach left bottom
corner, i.e., (R-1, 0). The second traversal starts from top right corner, i.e., (0, C-1) and
should reach bottom right corner, i.e., (R-1, C-1)/
2) From a point (i, j), we can move to (i+1, j+1) or (i+1, j-1) or (i+1, j)
3) A traversal gets all points of a particular cell through which it passes. If one traversal
has already collected points of a cell, then the other traversal gets no points if goes through
that cell again.

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 :

First traversal collects total points of value 3 + 2 + 20 + 1 + 1 = 27

238
Chapter 32. Collect maximum points in a grid using two traversals

Second traversal collects total points of value 2 + 4 + 10 + 20 + 10 = 46.


Total Points collected = 27 + 46 = 73.

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.

Both traversals always move forward along x


Base Cases:
// If destinations reached
if (x == R-1 && y1 == 0 && y2 == C-1)
maxPoints(arr, x, y1, y2) = arr[x][y1] + arr[x][y2];

// If any of the two locations is invalid (going out of grid)


if input is not valid
maxPoints(arr, x, y1, y2) = -INF (minus infinite)

// 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]

result += max { // Max of 9 cases


maxPoints(arr, x+1, y1+1, y2),
maxPoints(arr, x+1, y1+1, y2+1),
maxPoints(arr, x+1, y1+1, y2-1),
maxPoints(arr, x+1, y1-1, y2),
maxPoints(arr, x+1, y1-1, y2+1),
maxPoints(arr, x+1, y1-1, y2-1),
maxPoints(arr, x+1, y1, y2),
maxPoints(arr, x+1, y1, y2+1),
maxPoints(arr, x+1, y1, y2-1)
}

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

gramming) based implementation. In below implementation, we use a memoization table


‘mem’ to keep track of already solved problems.

// A Memoization based program to find maximum collection


// using two traversals of a grid
#include<bits/stdc++.h>
using namespace std;
#define R 5
#define C 4
  
// checks whether a given input is valid or not
bool isValid(int x, int y1, int y2)
{
    return (x >= 0 && x < R && y1 >=0 &&
            y1 < C && y2 >=0 && y2 < C);
}
  
// Driver function to collect max value
int getMaxUtil(int arr[R][C], int mem[R][C][C], int x, int y1, int y2)
{
    /*---------- BASE CASES -----------*/
    // if P1 or P2 is at an invalid cell
    if (!isValid(x, y1, y2)) return INT_MIN;
  
    // if both traversals reach their destinations
    if (x == R-1 && y1 == 0 && y2 == C-1)
       return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2];
  
    // If both traversals are at last row but not at their destination
    if (x == R-1) return INT_MIN;
  
    // If subproblem is already solved
    if (mem[x][y1][y2] != -1) return mem[x][y1][y2];
  
    // Initialize answer for this subproblem
    int ans = INT_MIN;
  
    // this variable is used to store gain of current cell(s)
    int temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2];
  
    /* Recur for all possible cases, then store and return the
       one with max value */
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1));
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1));
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2));
  
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2));
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1));

240
Chapter 32. Collect maximum points in a grid using two traversals

    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1));


  
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2));
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1));
    ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1));
  
    return (mem[x][y1][y2] = ans);
}
  
// This is mainly a wrapper over recursive function getMaxUtil().
// This function creates a table for memoization and calls
// getMaxUtil()
int geMaxCollection(int arr[R][C])
{
    // Create a memoization table and initialize all entries as -1
    int mem[R][C][C];
    memset(mem, -1, sizeof(mem));
  
    // Calculation maximum value using memoization based function
    // getMaxUtil()
    return getMaxUtil(arr, mem, 0, 0, C-1);
}
  
// Driver program to test above functions
int main()
{
    int arr[R][C] = {{3, 6, 8, 2},
                     {5, 2, 4, 3},
                     {1, 1, 20, 10},
                     {1, 1, 20, 10},
                     {1, 1, 20, 10},
                    };
    cout << "Maximum collection is " << geMaxCollection(arr);
    return 0;
}

Output:

Maximum collection is 73

Thanks to Gaurav Ahirwar for suggesting above problem and solution.

Source

https://www.geeksforgeeks.org/collect-maximum-points-in-a-grid-using-two-traversals/

241
Chapter 33

Common elements in all rows of


a given matrix

Common elements in all rows of a given matrix - GeeksforGeeks


Given an m x n matrix, find all common elements present in all rows in O(mn) time and
one traversal of matrix.
Example:

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.

// A Program to prints common element in all


// rows of matrix
#include <iostream>
#include <unordered_map>
using namespace std;
  
// Specify number of rows and columns
#define M 4
#define N 5
  
// prints common element in all rows of matrix
void printCommonElements(int mat[M][N])
{
    unordered_map<int, int> mp;
  
    // initalize 1st row elements with value 1
    for (int j = 0; j < N; j++)
        mp[mat[0][j]] = 1;
  
    // traverse the matrix
    for (int i = 1; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            // If element is present in the map and
            // is not duplicated in current row.
            if (mp[mat[i][j]] == i)
            {
               // we increment count of the element
               // in map by 1
                mp[mat[i][j]] = i + 1;
  
                // If this is last row
                if (i==M-1)
                  cout << mat[i][j] << " ";
            }
        }
    }
}
  
// driver program to test above function
int main()
{

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

Construct Ancestor Matrix


from a Given Binary Tree

Construct Ancestor Matrix from a Given Binary Tree - GeeksforGeeks


Given a Binary Tree where all values are from 0 to n-1. Construct an ancestor matrix
mat[n][n]. Ancestor matrix is defined as below.

mat[i][j] = 1 if i is ancestor of j
mat[i][j] = 0, otherwise

Examples:

Input: Root of below Binary Tree.


0
/ \
1 2
Output: 0 1 1
0 0 0
0 0 0

Input: Root of below Binary Tree.


5
/ \
1 2
/ \ /
0 4 3
Output: 0 0 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0

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.

// C++ program to construct ancestor matrix for


// given tree.
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
  
/* A binary tree node */
struct Node
{
    int data;
    Node *left, *right;
};
  
// Creating a global boolean matrix for simplicity
bool mat[MAX][MAX];
  
// anc[] stores all ancestors of current node.  This
// function fills ancestors for all nodes.
// It also returns size of tree.  Size of tree is
// used to print ancestor matrix.
int ancestorMatrixRec(Node *root, vector<int> &anc)
{
    /* base case */
    if (root == NULL) return 0;;
  
    // Update all ancestors of current node
    int data = root->data;
    for (int i=0; i<anc.size(); i++)
       mat[anc[i]][data] = true;
  
    // Push data to list of ancestors
    anc.push_back(data);
  
    // Traverse left and right subtrees
    int l = ancestorMatrixRec(root->left, anc);

246
Chapter 34. Construct Ancestor Matrix from a Given Binary Tree

    int r = ancestorMatrixRec(root->right, anc);


  
    // Remove data from list the list of ancestors
    // as all descendants of it are processed now.
    anc.pop_back();
  
    return l+r+1;
}
  
// This function mainly calls ancestorMatrixRec()
void ancestorMatrix(Node *root)
{
    // Create an empty ancestor array
    vector<int> anc;
  
    // Fill ancestor matrix and find size of
    // tree.
    int n = ancestorMatrixRec(root, anc);
  
    // Print the filled values
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<n; j++)
            cout << mat[i][j] << " ";
        cout << endl;
    }
}
  
/* Helper function to create a new node */
Node* newnode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
/* Driver program to test above functions*/
int main()
{
    /* Construct the following binary tree
                5
              /   \
            1      2
          /  \    /
         0    4  3    */
    Node *root        = newnode(5);
    root->left        = newnode(1);

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

Time complexity of above solution is O(n2 ).


How to do reverse – construct tree from ancestor matrix?
Construct tree from ancestor matrix
This article is contributed by Dheeraj 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/construct-ancestor-matrix-from-a-given-binary-tree/

248
Chapter 35

Construct a linked list from 2D


matrix

Construct a linked list from 2D matrix - GeeksforGeeks


Given a matrix. Convert it into a linked list matrix such that each node is connected to its
next right and down node.
Example:

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

Question Source : Factset Interview Experience | Set 9


The idea is to construct a new node for every element of matrix and recursively create its
down and right nodes.

C++

249
Chapter 35. Construct a linked list from 2D matrix

// CPP program to construct a linked list


// from given 2D matrix
#include <bits/stdc++.h>
using namespace std;
  
// struct node of linked list
struct Node {
    int data;
    Node* right, *down;
};
  
// returns head pointer of linked list
// constructed from 2D matrix
Node* construct(int arr[][3], int i, int j, 
                              int m, int n)
{
    // return if i or j is out of bounds
    if (i > n - 1 || j > m - 1)
        return NULL;
  
    // create a new node for current i and j
    // and recursively allocate its down and
    // right pointers
    Node* temp = new Node();
    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
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) {
        Rp = Dp;
  
        // loop till node->right is not NULL
        while (Rp) {
            cout << Rp->data << " ";
            Rp = Rp->right;

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

// Java program to construct a linked list


// from given 2D matrix
public class Linked_list_2D_Matrix {
  
    // node of linked list
    static class Node {
        int data;
        Node right;
        Node down;
    };
  
    // returns head pointer of linked list
    // constructed from 2D matrix
    static Node construct(int arr[][], int i, int j, 
                                     int m, int n) {
          
        // return if i or j is out of bounds
        if (i > n - 1 || j > m - 1)
            return null;
  
        // create a new node for current i and j
        // and recursively allocate its down and
        // right pointers
        Node temp = new Node();

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

Construct a linked list from 2D


matrix (Iterative Approach)

Construct a linked list from 2D matrix (Iterative Approach) - GeeksforGeeks


Given a matrix, the task is to construct a linked list matrix in which each node is connected
to its right and down node.
Example:

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.

Below is the implementation of the above approach:

// C++ program to construct a linked


// list from 2D matrix | Iterative Approach
#include <bits/stdc++.h>
using namespace std;
  
// struct node of linked list
struct node {
    int data;
    node *right, *down;
};
  
// utility function to create a new node with given data
node* newNode(int d)
{
    node* temp = new node;
    temp->data = d;
    temp->right = temp->down = NULL;
    return temp;
}
  

255
Chapter 36. Construct a linked list from 2D matrix (Iterative Approach)

// utility function to print the linked list pointed to by head pointer


void display(node* head)
{
    node *rp, *dp = head;
  
    // loop until the down pointer is not NULL
    while (dp) {
        rp = dp;
  
        // loop until the right pointer is not NULL
        while (rp) {
            cout << rp->data << " ";
            rp = rp->right;
        }
        cout << endl;
        dp = dp->down;
    }
}
  
// function which constructs the linked list
// from the given matrix of size m * n
// and returns the head pointer of the linked list
node* constructLinkedMatrix(int mat[][3], int m, int n)
{
    // stores the head of the linked list
    node* mainhead = NULL;
  
    // stores the head of linked lists of each row
    node* head[m];
    node *righttemp, *newptr;
  
    // Firstly, we create m linked lists
    // by setting all the right nodes of every row
    for (int i = 0; i < m; i++) {
  
        // initially set the head of ith row as NULL
        head[i] = NULL;
        for (int j = 0; j < n; j++) {
            newptr = newNode(mat[i][j]);
  
            // stores the mat[0][0] node as
            // the mainhead of the linked list
            if (!mainhead)
                mainhead = newptr;
  
            if (!head[i])
                head[i] = newptr;
            else

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

Time complexity: O(M * N)


Improved By : souravdutta123

Source

https://www.geeksforgeeks.org/construct-a-linked-list-from-2d-matrix-iterative-approach/

258
Chapter 37

Construct a unique matrix n x


n for an input n

Construct a unique matrix n x n for an input n - GeeksforGeeks


Given an odd integer n, find a matrix of size n x n with following conditions:

1. Each cell contains an integer from 1 and n (inclusive).


2. No integer appears twice in the same row or the same column.
3. All 1’s must be at every possible distance from the center of the matrix. The center
of a n x n square is cell ((n-1)/2, (n-1)/2) for odd n.

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++

// C++ program to construct an n x n 


// matrix such that every row and every 
// column has distinct values.
#include <iostream>
#include <bits/stdc++.h>
  
using namespace std;
  
const int MAX = 100;
int mat[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.
void fillRemaining(int i, int j, int n)
{
    // Initialize value to be filled
    int x = 2;
  

260
Chapter 37. Construct a unique matrix n x n for an input n

    // 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
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++;
        }
    }

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

// Java program to construct an n x n 


// matrix such that every row and every
// column has distinct values.
class GFG
{
      
    static final 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++;

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

    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()
    {
        int n = 5;
      
        // Passing n to constructMatrix function
        constructMatrix(n);
      
        // Printing the desired unique matrix
        for (int i = 0; i < n; i++)

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

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/construct-unique-matrix-n-x-n-input-n/

266
Chapter 38

Construct tree from ancestor


matrix

Construct tree from ancestor matrix - GeeksforGeeks


Given an ancestor matrix mat[n][n] where Ancestor matrix is defined as below.

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.

This problem is mainly reverse of below problem.


Construct Ancestor Matrix from a Given Binary Tree
We strongly recommend you to minimize your browser and try this yourself
first.
Observations used in the solution:

1. The rows that correspond to leaves have all 0’s


2. The row that corresponds to root has maximum number of 1’s.
3. Count of 1’s in i’th row indicates number of descendants of node i.

The idea is to construct the tree in bottom up manner.


1) Create an array of node pointers node[].
2) Store row numbers that correspond to a given count. We have used multimap for this
purpose.
3) Process all entries of multimap from smallest count to largest (Note that entries in map
and multimap can be traversed in sorted order). Do following for every entry.
…….a) Create a new node for current row number.
…….b) If this node is not a leaf node, consider all those descendants of it whose parent is
not set, make current node as its parent.
4) The last processed node (node with maximum sum) is root of tree.
Below is C++ implementation of above idea. Following are steps.

// Given an ancestor matrix for binary tree, construct


// the tree.
#include <bits/stdc++.h>
using namespace std;
  
# define N 6
  

268
Chapter 38. Construct tree from ancestor matrix

/* A binary tree node */


struct Node
{
    int data;
    Node *left, *right;
};
  
/* Helper function to create a new node */
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Constructs tree from ancestor matrix
Node* ancestorTree(int mat[][N])
{
    // Binary array to determine weather
    // parent is set for node i or not
    int parent[N] = {0};
  
    // Root will store the root of the constructed tree
    Node* root = NULL;
  
    // Create a multimap, sum is used as key and row
    // numbers are used as values
    multimap<int, int> mm;
  
    for (int i = 0; i < N; i++)
    {
        int sum = 0; // Initialize sum of this row
        for (int j = 0; j < N; j++)
            sum += mat[i][j];
  
        // insert(sum, i) pairs into the multimap
        mm.insert(pair<int, int>(sum, i));
    }
  
    // node[i] will store node for i in constructed tree
    Node* node[N];
  
    // Traverse all entries of multimap.  Note that values
    // are accessed in increasing order of sum
    for (auto it = mm.begin(); it != mm.end(); ++it)
    {
      // create a new node for every value

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:

Inorder traversal of tree is


0 1 4 5 3 2

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

Conway’s Game Of Life


(Python Implementation)

Conway’s Game Of Life (Python Implementation) - GeeksforGeeks


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..

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. Initialize the cells in the grid.


2. At each time step in the simulation, for each
cell (i, j) in the grid, do the following:
a. Update the value of cell (i, j) based on
its neighbors, taking into account the
boundary conditions.
b. Update the display of grid values.

After we done here lets get our hands on code.


Requirements

1. numpy
2. matplotlib
3. argparse

Now lets get it started


The Code

# Python code to implement Conway's Game Of Life


import argparse
import numpy as np
import matplotlib.pyplot as plt 

273
Chapter 39. Conway’s Game Of Life (Python Implementation)

import matplotlib.animation as animation


  
# setting up the values for the grid
ON = 255
OFF = 0
vals = [ON, OFF]
  
def randomGrid(N):
  
    """returns a grid of NxN random values"""
    return np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)
  
def addGlider(i, j, grid):
  
    """adds a glider with top left cell at (i, j)"""
    glider = np.array([[0,    0, 255], 
                       [255,  0, 255], 
                       [0,  255, 255]])
    grid[i:i+3, j:j+3] = glider
  
def addGosperGliderGun(i, j, grid):
  
    """adds a Gosper Glider Gun with top left
       cell at (i, j)"""
    gun = np.zeros(11*38).reshape(11, 38)
  
    gun[5][1] = gun[5][2] = 255
    gun[6][1] = gun[6][2] = 255
  
    gun[3][13] = gun[3][14] = 255
    gun[4][12] = gun[4][16] = 255
    gun[5][11] = gun[5][17] = 255
    gun[6][11] = gun[6][15] = gun[6][17] = gun[6][18] = 255
    gun[7][11] = gun[7][17] = 255
    gun[8][12] = gun[8][16] = 255
    gun[9][13] = gun[9][14] = 255
  
    gun[1][25] = 255
    gun[2][23] = gun[2][25] = 255
    gun[3][21] = gun[3][22] = 255
    gun[4][21] = gun[4][22] = 255
    gun[5][21] = gun[5][22] = 255
    gun[6][23] = gun[6][25] = 255
    gun[7][25] = 255
  
    gun[3][35] = gun[3][36] = 255
    gun[4][35] = gun[4][36] = 255
  

274
Chapter 39. Conway’s Game Of Life (Python Implementation)

    grid[i:i+11, j:j+38] = gun


  
def update(frameNum, img, grid, N):
  
    # copy grid since we require 8 neighbors 
    # for calculation and we go line by line 
    newGrid = grid.copy()
    for i in range(N):
        for j in range(N):
  
            # compute 8-neghbor sum
            # using toroidal boundary conditions - x and y wrap around 
            # so that the simulaton takes place on a toroidal surface.
            total = int((grid[i, (j-1)%N] + grid[i, (j+1)%N] + 
                         grid[(i-1)%N, j] + grid[(i+1)%N, j] + 
                         grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] + 
                         grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])/255)
  
            # apply Conway's rules
            if grid[i, j]  == ON:
                if (total < 2) or (total > 3):
                    newGrid[i, j] = OFF
            else:
                if total == 3:
                    newGrid[i, j] = ON
  
    # update data
    img.set_data(newGrid)
    grid[:] = newGrid[:]
    return img,
  
# main() function
def main():
  
    # Command line args are in sys.argv[1], sys.argv[2] ..
    # sys.argv[0] is the script name itself and can be ignored
    # parse arguments
    parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.")
  
    # add arguments
    parser.add_argument('--grid-size', dest='N', required=False)
    parser.add_argument('--mov-file', dest='movfile', required=False)
    parser.add_argument('--interval', dest='interval', required=False)
    parser.add_argument('--glider', action='store_true', required=False)
    parser.add_argument('--gosper', action='store_true', required=False)
    args = parser.parse_args()
      
    # set grid size

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()

Without passing any command line arguments.

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.

python 'filename.py' --grid-size 32 --interval 500 --glider

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:

1. Github Code for this article


2. Book: Python Playground: Geeky Projects for the Curious Programmer
3. docs-numpy
4. docs matplotlib

Source

https://www.geeksforgeeks.org/conways-game-life-python-implementation/

277
Chapter 40

Count Negative Numbers in a


Column-Wise and Row-Wise
Sorted Matrix

Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix - GeeksforGeeks


Find the number of negative numbers in a column-wise / row-wise sorted matrix M[][].
Suppose M has n rows and m columns.
Example:

Input: M = [-3, -2, -1, 1]


[-2, 2, 3, 4]
[4, 5, 7, 8]
Output : 4
We have 4 negative numbers in this matrix

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:

[-3, -2, -1, 1]


[-2, 2, 3, 4]
[4, 5, 7, 8]

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]

Below is the implementation of above idea.

C++

// CPP implementation of Naive method


// to count of negative numbers in 
// M[n][m]
#include <bits/stdc++.h>
using namespace std;
  
int countNegative(int M[][4], int n, int m)
{
    int count = 0;
  
    // 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 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);

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

//Java implementation of Naive method


// to count of negative numbers in 
// M[n][m]
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{
    static int countNegative(int M[][], int n, 
                                      int m)
    {
        int count = 0;
  
        // 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 program to test above functions
    public static void main (String[] args) 
    {
    int M[][] = { {-3, -2, -1, 1},
                  {-2, 2, 3, 4},
                  {4, 5, 7, 8} };
      
    System.out.println(countNegative(M, 3, 4));
    }
}

280
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix

// This code is contributed by Chhavi

Python

# Python implementation of Naive method to count of 


# negative numbers in M[n][m]
  
def countNegative(M, n, m):
    count = 0
  
    # Follow the path shown using arrows above
    for i in range(n):
        for j in range(m): 
  
            if M[i][j] < 0:
                count += 1
  
            else:
                # no more negative numbers in this row
                break
    return count
  
  
# Driver code
M = [ 
      [-3, -2, -1,  1],
      [-2,  2,  3,  4],
      [ 4,  5,  7,  8]
    ]
print(countNegative(M, 3, 4))

C#

// C# implementation of Naive 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)
    {
        int count = 0;

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.

With the given example:


[-3, -2, -1, 1]
[-2, 2, 3, 4]
[4, 5, 7, 8]

283
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix

Here's the idea:


[-3, -2, ?, ?] -> Found 3 negative numbers in this row
[ ?, ?, ?, 4] -> Found 1 negative number in this row
[ ?, 5, 7, 8] -> No negative numbers in this row

C++

// CPP implementation of Efficient 


// method to count of negative numbers
// in M[n][m]
#include <bits/stdc++.h>
using namespace std;
  
int countNegative(int M[][4], 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
            // in this row. So there
            // must be ( j+1 )
            count += j + 1;
  
            // negative numbers in 
            // this row.
            i += 1;
        }
              
        // move to the left and see 
        // if we can find a negative
        // number there
        else
        j -= 1;
    }
  
    return count;

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

// Java implementation of Efficient 


// method to count of negative numbers
// in M[n][m]
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{
    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
                // in this row. So there
                // must be ( j+1 )
                count += j + 1;
  

285
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix

                // negative numbers in 


                // this row.
                i += 1;
            }
              
            // move to the left and see 
            // if we can find a negative
            // number there
            else
            j -= 1;
        }
        return count;
    }
  
    // Driver program to test above functions
    public static void main (String[] args) 
    {
    int M[][] = { {-3, -2, -1, 1},
                    {-2, 2, 3, 4},
                    {4, 5, 7, 8} };
      
    System.out.println(countNegative(M, 3, 4));
    }
}
// This code is contributed by Chhavi

Python

# Python implementation of Efficient method to count of 


# negative numbers in M[n][m]
  
def countNegative(M, n, m):
  
    count = 0 # initialize result
  
    # Start with top right corner
    i = 0 
    j = m - 1  
  
    # Follow the path shown using arrows above
    while j >= 0 and i < n:
  
        if M[i][j] < 0:
  
            # j is the index of the last negative number
            # in this row.  So there must be ( j+1 )
            count += (j + 1) 
  

286
Chapter 40. Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix

            # negative numbers in this row.


            i += 1
  
        else:
            # move to the left and see if we can
            # find a negative number there
             j -= 1
    return count
  
# Driver code
M = [ 
      [-3, -2, -1,  1],
      [-2,  2,  3,  4],
      [4,   5,  7,  8]
    ]
print(countNegative(M, 3, 4))

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

                // in this row. So there


                // must be ( j + 1 )
                count += j + 1;
  
                // negative numbers in 
                // this row.
                i += 1;
            }
              
            // move to the left and see 
            // if we can find a negative
            // number there
            else
            j -= 1;
        }
        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 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

    // Follow the path shown using


    // arrows above
    while( $j >= 0 and $i < $n )
    {
        if( $M[$i][$j] < 0 )
        {
            // j is the index of the
            // last negative number
            // in this row. So there
            // must be ( j+1 )
            $count += $j + 1;
  
            // negative numbers in 
            // this row.
            $i += 1;
        }
              
        // move to the left and see 
        // if we can find a negative
        // number there
        else
        $j -= 1;
    }
  
    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);
      
    return 0; 
  
// This code is contributed by anuj_67.
?>

Output :

With this solution, we can now solve this problem in O(n + m) time.

Improved By : Sam007, vt_m

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

Count all 0s which are blocked


by 1s in binary matrix

Count all 0s which are blocked by 1s in binary matrix - GeeksforGeeks


Given Binary matrix. Task is count all zeros which are surrounded by one (may not be
immediate neighbor).
Note: here we are only taking four direction up, left, down, right.
Examples:

Input : Int M[][] = {{ 0, 1, 1, 0},


{ 1, 0, 0, 1},
{ 0, 1, 0, 1},
{ 1, 0, 1, 1}}
Output : 3
Explanation : All zeros which are surrounded
by 1 are (1, 1), (1, 2) and (2, 2)

Idea is based on the DFS.


First we remove all the zero value cells in the matrix which are reachable from boundary
of Matrix using DFS. Note that any cell which is reachable from a boundary 0 cell is not
surrounded by ones.

Int M[][] = {{ 0, 1, 1, 0},


{ 1, 0, 0, 1},
{ 0, 1, 1, 1},
{ 1, 0, 1, 1}}
All zero cell which are reachable from boundary are in read color.

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.

// c++ program to count number of zeros


// surrounded by 1
#include <iostream>
using namespace std;
#define Row 4
#define Col 5
int r[4] = { 0, 0, 1, -1 };
int c[4] = { 1, -1, 0, 0 };
  
bool isSafe(int x, int y, int M[][Col])
{
    if (x >= 0 && x <= Row && y >= 0 &&
        y <= Col && M[x][y] == 0)
        return true;
    return false;
}
  
// DFS function to mark all reachable cells from
// (x, y)
void DFS(int x, int y, int M[][Col])
{
    // make it's visited
    M[x][y] = 1;
    for (int k = 0; k < 4; k++)
        if (isSafe(x + r[k], y + c[k], M))
            DFS(x + r[k], y + c[k], M);
}
  
// function return count of 0's which are surrounded by 1
int CountAllZero(int M[][Col])
{
    // first we remove all zeros which are not
    // surrounded by 1 that means we only remove 
    // those zeros which are reachable from
    // any boundary of given matrix.
    for (int i = 0; i < Col; i++)
        if (M[0][i] == 0)
            DFS(0, i, M);
    for (int i = 0; i < Col; i++)
        if (M[Row - 1][i] == 0)
            DFS(Row - 1, i, M);
    for (int i = 0; i < Row; i++)
        if (M[i][0] == 0)
            DFS(i, 0, M);
    for (int i = 0; i < Row; i++)

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:

Time Complexity: O(Row*Col)

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

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

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)
{
   // If either given row number is first or given column 
   // number is first
   if (m == 1 || n == 1)
        return 1;
  
   // If diagonal movements are allowed then the last 
   // addition is required.
   return  numberOfPaths(m-1, n) + numberOfPaths(m, n-1);
           // + numberOfPaths(m-1,n-1);
}
  
int main()
{
    cout << numberOfPaths(3, 3);
    return 0;
}

Java

// A Java program to count all possible paths 


// from top left to bottom right
  
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)
    {
        // If either given row number is first or 
        // given column number is first
        if (m == 1 || n == 1)
            return 1;
   
        // If diagonal movements are allowed then 
        // the last addition is required.
        return  numberOfPaths(m-1, n) + numberOfPaths(m, n-1);
                // + numberOfPaths(m-1,n-1);
    }
   

295
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix

    public static void main(String args[])


    {
       System.out.println(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by Sumit Ghosh

Python

# Python program to count all possible paths 


# from top left to bottom right
   
# function to return count of possible paths
# to reach cell at row number m and column
# number n from the topmost leftmost
# cell (cell at 1, 1)
def numberOfPaths(m, n):
   # If either given row number is first
   # or given column number is first
   if(m == 1 or n == 1):
        return 1
    
   # If diagonal movements are allowed
   # then the last addition
   # is required.
   return  numberOfPaths(m-1, n) + numberOfPaths(m, n-1)
  
# Driver program to test above function  
m = 3
n = 3
print(numberOfPaths(m, n))
  
# This code is contributed by Aditi Sharma

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

Like other typical Dynamic Programming(DP) problems, recomputations of same subprob-


lems can be avoided by constructing a temporary array count[][] in bottom up manner using
the above recursive formula.
C

#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

// A Java program to count all possible paths 

297
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix

// from top left to bottom right


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 2D table to store results 
        // of subproblems
        int count[][] = new int[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 function
    public static void main(String args[])
    {
        System.out.println(numberOfPaths(3, 3));
    }
}
  
// This code is contributed by Sumit Ghosh

Python

298
Chapter 42. Count all possible paths from top left to bottom right of a mXn matrix

# Python program to count all possible paths 


# from top left to bottom right
  
# 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)
def numberOfPaths(m, n):
    # Create a 2D table to store
    # results of subproblems
    count = [[0 for x in range(m)] for y in range(n)]
    
    # Count of paths to reach any 
    # cell in first column is 1
    for i in range(m):
        count[i][0] = 1;
    
    # Count of paths to reach any 
    # cell in first column is 1
    for j in range(n):
        count[0][j] = 1;
    
    # Calculate count of paths for other
    # cells in bottom-up 
    # manner using the recursive solution
    for i in range(1, m):
        for j in range(n):             
            count[i][j] = count[i-1][j] + count[i][j-1]
    return count[m-1][n-1]
  
# Driver program to test above function 
m = 3
n = 3
print( numberOfPaths(m, n))
  
# This code is contributed by Aditi Sharma

Output:

Time complexity of the above dynamic programming solution is O(mn).


The space complexity of the above solution is O(mn).
Space Optimization of DP solution.
Above solution is more intuitive but we can also reduce the space by O(n); where n is column
size.
Java

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:

This code is contributed by Vivek Singh


Note the count can also be calculated using the formula (m-1 + n-1)!/(m-1)!(n-1)!.
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
Improved By : viveksingh14

Source

https://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/

300
Chapter 43

Count all sorted rows in a


matrix

Count all sorted rows in a matrix - GeeksforGeeks


Given a matrix of m*n size, the task is to count all the rows in a matrix that are sorted
either in strictly increasing order or in strictly decreasing order?
Examples :

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

The idea is simple and involves two traversals of matrix.


1) Traverse from left side of the matrix to count all the row which are in strictly increasing
order
2) Traverse from right side of the matrix to count all the row which are in strictly de-
creasing order
Below is the implementation of above idea.

C++

// C++ program to find number of sorted rows


#include <bits/stdc++.h>
#define MAX 100
using namespace std;
  

301
Chapter 43. Count all sorted rows in a matrix

// Function to count all sorted rows in a matrix


int sortedCount(int mat[][MAX], int r, int c)
{
    int result = 0; // Initialize result
  
    // Start from left side of matrix to
    // count increasing order rows
    for (int i=0; i<r; i++)
    {
        // Check if there is any pair ofs element
        // that are  not in increasing order.
        int 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 )
    for (int i=0; i<r; i++)
    {
        // Check if there is any pair ofs element
        // that are  not in decreasing order.
        int j;
        for (j=c-1; j>0; j--)
            if (mat[i][j-1] <= mat[i][j])
                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 program to run the case
int main()
{
    int m = 4, n = 5;

302
Chapter 43. Count all sorted rows in a matrix

    int mat[][MAX] = {{1, 2, 3, 4, 5},


                      {4, 3, 1, 2, 6},
                      {8, 7, 6, 5, 4},
                      {5, 7, 8, 9, 10}};
    cout << sortedCount(mat, m, n);
    return 0;
}

Java

// Java program to find number of sorted rows


  
class GFG {
      
    static int MAX = 100;
  
    // Function to count all sorted rows in a matrix
    static int sortedCount(int mat[][], int r, int c)
    {
        int result = 0; // Initialize result
  
        // Start from left side of matrix to
        // count increasing order rows
        for (int i = 0; i < r; i++) {
              
            // Check if there is any pair ofs element
            // that are not in increasing order.
            int 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 )
        for (int i = 0; i < r; i++) {
              
            // Check if there is any pair ofs element
            // that are not in decreasing order.
            int j;
            for (j = c - 1; j > 0; j--)
                if (mat[i][j - 1] <= mat[i][j])

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#

// C# program to find number of sorted rows


using System;
  
class GFG {
      
// static int MAX = 100;
  
    // Function to count all sorted rows in 
    // a matrix
    static int sortedCount(int [,]mat, int r,
                                       int c)
    {
        int result = 0; // Initialize result
  
        // Start from left side of matrix to
        // count increasing order rows
        for (int i = 0; i < r; i++) {
              
            // Check if there is any pair of
            // element that are not in

304
Chapter 43. Count all sorted rows in a matrix

            // increasing order.


            int 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 )
        for (int i = 0; i < r; i++) {
              
            // Check if there is any pair 
            // ofs element that are not in
            // decreasing order.
            int j;
            for (j = c - 1; j > 0; j--)
                if (mat[i,j - 1] <= mat[i,j])
                    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()
    {
        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 } };

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

    for ($i = 0; $i < $r; $i++)


    {
        // Check if there is any pair 
        // ofs element that are not
        // in decreasing order.
        $j;
        for ($j = $c - 1; $j > 0; $j--)
            if ($mat[$i][$j - 1] <= $mat[$i][$j])
                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
$m = 4; $n = 5;
$mat = array(array(1, 2, 3, 4, 5),
             array(4, 3, 1, 2, 6),
             array(8, 7, 6, 5, 4),
             array(5, 7, 8, 9, 10));
echo sortedCount($mat, $m, $n);
  
// This code is contributed by anuj_67.
?>

Output :

Time Complexity : O(m*n)


Auxiliary space : O(1)
If you have another optimized approach to solve this problem then please share in comments.
Improved By : vt_m

Source
https://www.geeksforgeeks.org/count-sorted-rows-matrix/

307
Chapter 44

Count elements smaller than or


equal to x in a sorted matrix

Count elements smaller than or equal to x in a sorted matrix - GeeksforGeeks


Given a n x n strictly sorted matrix and a value x. The problem is to count the elements
smaller than or equal to x in the given matrix. Here strictly sorted matrix means that
matrix is 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 or equal to the last
element of row ’i-1’.
Examples:

Input : mat[][] = { {1, 4, 5},


{6, 10, 11},
{12, 15, 20} }
x = 9
Output : 4
The elements smaller than '9' are:
1, 4, 5 and 6.

Input : mat[][] = { {1, 4, 7, 8},


{10, 10, 12, 14},
{15, 26, 30, 31},
{31, 42, 46, 50} }
x = 31
Output : 13

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++

// C++ implementation to count elements smaller than


// or equal to x in a sorted matrix
#include <bits/stdc++.h>
  
using namespace std;
  
#define 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.
int binarySearchOnRow(int mat[SIZE][SIZE],
                      int l, int h, int x)
{
    while (l <= h) {
        int 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
    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'.
int binarySearchOnCol(int mat[SIZE][SIZE],
                      int l, int h, int x, int row)

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

    cout << "Count = "


         << countSmallElements(mat, n, x);
    return 0;
}

Java

//Java implementation to count elements 


// smaller than or equal to x in a sorted matrix
import java.io.*;
  
class GFG {
  
static int 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.
static int binarySearchOnRow(int[][] mat,
                        int l, int h, int x)
{
    while (l <= h) {
      
        int 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
    return h;
}
  
// function returns the column index
// no of largest element
// smaller than equal to 'x' in 

311
Chapter 44. Count elements smaller than or equal to x in a sorted matrix

// 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);
  
    // required count of elements
    return ((row_no) * n) + (col_no + 1);
}
  

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#

//Java implementation to count elements 


// smaller than or equal to x in a sorted matrix
using System;
  
class GFG {
  
    //static int 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.
    static int binarySearchOnRow(int [,] mat, int l,
                                 int h, int x)
    {
        while (l <= h) {
          
            int 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
        return h;

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

Time Complexity: O(Log2 n).


Improved By : nitin mittal

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

Count entries equal to x in a


special matrix

Count entries equal to x in a special matrix - GeeksforGeeks


You are given a square matrix (matrix[][]) of order n, where matrix[i][j] = i*j. Find the
number of cells which have entry equal to a given number x.
NOte : Indexing of matrix starts from 1, i.e. 1<= i,j <= n.
Examples :

Input : matrix[][] = {1, 2, 3, 4,


2, 4, 6, 8,
3, 6, 9, 12,
4, 8, 12, 16}
x = 4
Output : 3

Input : matrix[][] = {1, 2, 3, 4,


2, 4, 6, 8,
3, 6, 9, 12,
4, 8, 12, 16}
x = 12
Output : 2

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).

// traverse and check whole matrix

321
Chapter 45. Count entries equal to x in a special matrix

for (int i=1; i<=n ; i++)


{
for (int j=1; j<=n; j++)
if (i * j == x)
count++;
}
// return count
return count;

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).

// traverse and find the factors


for (int i=1; i<=n && 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 && x%i ==0)
count++;
}
// return count
return count;

C++

// CPP program for counting number of cell 


// equals to given x
#include<bits/stdc++.h>
using namespace std;
  
// function to count factors as number of cell
int count (int n, int x)
{
    int count == 0;
    // traverse and find the factors
    for (int i=1; i<=n && 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 && x%i ==0)
            count++;
    }
    // return count 
    return count;
}

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

// Java program for counting number of


// cell equals to given x
class GFG
{
    // function to count factors as 
    // number of cell
    static int count (int n, int x)
    {
        int count = 0;
      
        // traverse and find the factors
        for (int i = 1; i <= n && 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 && x % i == 0)
                count++;
        }
          
        // return count 
        return count;
    }
  
    // driver program
    public static void main(String args[])
    {
        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;

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#

// C# program for counting number


// of cell equals to given x
using System; 
  
class GFG {
      
    // function to count factors as 
    // number of cell
    static int count (int n, int x) {
          
        int count = 0;
      
        // traverse and find the factors
        for (int i = 1; i <= n && 
             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 && x % i == 0)
                count++;
        }
          
        // return count 
        return count;
    }
  
    // Driver Code
    public static void 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;
        Console.Write(count(n, x));
    }
}

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 :

Improved By : nitin mittal, vt_m

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

Count frequency of k in a matrix of size n where matrix(i, j) = i+j - GeeksforGeeks


Given a matrix of size n*n. Count the frequency of given element k in that matrix. Here
base index is 1.
Examples:

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

// CPP program to find the frequency of k 


// in matrix where m(i, j)=i+j
#include <bits/stdc++.h>
using namespace std;
int find(int n, int k)
{
    if (n + 1 >= k)
        return (k - 1);
    else
        return (2 * n + 1 - k);
}

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

// Java program to find the 


// frequency of k in matrix
// in matrix where m(i, j)=i+j
import java.util.*;
import java.lang.*;
  
public class GfG{
  
    public static int find(int n, int k)
    {
        if (n + 1 >= k)
            return (k - 1);
        else
            return (2 * n + 1 - k);
    }
          
    // Driver function 
    public static void main(String argc[])
    {
        int n = 4, k = 7;
        int freq = find(n, k);
        if (freq < 0)
            System.out.print(" element"
            + " not exist \n ");
        else
            System.out.print(" Frequency"
            + " of " + k + " is " +
            freq + "\n");
    }
}
  
// This code is contributed by Sagar Shukla

329
Chapter 46. Count frequency of k in a matrix of size n where matrix(i, j) = i+j

Python3

# Python program to find


# the frequency of k 
# in matrix where
# m(i, j)=i+j
  
import math
  
def 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):
    print ( " element not exist")
else:
    print(" Frequency of " , k ," is " , freq )
  
# This code is contributed
# by Gitanjali.

C#

// C# program to find the 


// frequency of k in matrix
// in matrix where m(i, j)=i+j
using System;
  
public class GfG{
  
    public static int find(int n, int k)
    {
        if (n + 1 >= k)
            return (k - 1);
        else
            return (2 * n + 1 - k);
    }

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

Count inversion pairs in a


matrix

Count inversion pairs in a matrix - GeeksforGeeks


Given a matrix A of size NxN, we need to find the number of inversion pairs in it. Inversion
count in a matrix is defined as the number of pairs satisfying the following conditions :

• x1 � x2
• y1 � y2
• A[x2 ][y2 ] < A[x1 ][y1 ]

Constraints :

• 1 � Ai,j � 109
• 1 � N � 103

Examples:

For simplicity, let's take a 2x2 matrix :


A = {{7, 5},
{3, 1}};
The inversion pairs are : (7, 5), (3, 1), (7, 3), (5, 1) and (7, 1)
Output : 5

To solve this problem, we need to know the following things :

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 :

1. Initialize inv_pair_cnt = 0, which will store the number of inversion pairs.


2. Store the tuple (-A[i][j], i, j) in an array, say v, where A[i][j] is the
element of the matrix A at position (i, j).
3. Sort the array v according to the first element of the tuple, i.e.,
according to the value of -A[i][j].
4. Traverse the array v and do the following :
- Initialize an array, say 'pairs' to store the position (i, j)
of the tuples of v.
- while the current tuple of v and all its adjacent tuples whose
first value, i.e., -A[i][j] is same, do
- Push the current tuple's position pair (i, j) into 'pairs'.
- Add to inv_pair_cnt, the number of elements which are less than
the current element(i.e., A[i][j]) and lie on the right side
in the sorted array v, by calling the query operation of BIT and
passing i and j as arguments.
- For each position pair (i, j) stored in the array 'pairs',
update the position (i, j) in the 2D BIT by 1.
5. Finally, inv_pair_cnt will contain the number of inversion pairs.

Here is the C++ implementation :

// C++ program to count the number of inversion


// pairs in a 2D matrix
#include <bits/stdc++.h>
using namespace std;
  

334
Chapter 47. Count inversion pairs in a matrix

// for simplicity, we are taking N as 4


#define N 4
  
// Function to update a 2D BIT. It updates the
// value of bit[l][r] by adding val to bit[l][r]
void update(int l, int r, int val, int bit[][N + 1])
{
    for (int i = l; i <= N; i += i & -i)
        for (int j = r; j <= N; j += j & -j)
            bit[i][j] += val;
}
  
// function to find cumulative sum upto
// index (l, r) in the 2D BIT
long long query(int l, int r, int bit[][N + 1])
{
    long long ret = 0;
    for (int i = l; i > 0; i -= i & -i)
        for (int j = r; j > 0; j -= j & -j)
            ret += bit[i][j];
  
    return ret;
}
  
// function to count and return the number
// of inversion pairs in the matrix
long long countInversionPairs(int mat[][N])
{
    // the 2D bit array and initialize it with 0.
    int bit[N+1][N+1] = {0};
  
    // v will store the tuple (-mat[i][j], i, j)
    vector<pair<int, pair<int, int> > > v;
  
    // store the tuples in the vector v
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
  
            // Note that we are not using the pair
            // (0, 0) because BIT update and query
            // operations are not done on index 0
            v.push_back(make_pair(-mat[i][j],
                        make_pair(i+1, j+1)));
  
    // sort the vector v according to the
    // first element of the tuple, i.e., -mat[i][j]
    sort(v.begin(), v.end());
  

335
Chapter 47. Count inversion pairs in a matrix

    // inv_pair_cnt will store the number of


    // inversion pairs
    long long inv_pair_cnt = 0;
  
    // traverse all the tuples of vector v
    int i = 0;
    while (i < v.size())
    {
        int curr = i;
  
        // 'pairs' will store the position of each element,
        // i.e., the pair (i, j) of each tuple of the vector v
        vector<pair<int, int> > pairs;
  
        // consider the current tuple in v and all its
        // adjacent tuples whose first value, i.e., the
        // value of –mat[i][j] is same
        while (curr < v.size() &&
               (v[curr].first == v[i].first))
        {
            // push the position of the current element in 'pairs'
            pairs.push_back(make_pair(v[curr].second.first,
                                      v[curr].second.second));
  
            // add the number of elements which are
            // less than the current element and lie on the right
            // side in the vector v
            inv_pair_cnt += query(v[curr].second.first,
                                  v[curr].second.second, bit);
  
            curr++;
        }
  
        vector<pair<int, int> >::iterator it;
  
        // traverse the 'pairs' vector
        for (it = pairs.begin(); it != pairs.end(); ++it)
        {
            int x = it->first;
            int y = it->second;
  
            // update the positon (x, y) by 1
            update(x, y, 1, bit);
        }
  
        i = curr;
    }
  

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:

The number of inversion pairs are : 43

Time Complexity : O(log(NxN)), where N is the size of the matrix


Space Complexity : O(NxN)

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

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:

mat[M][N] = {{'O', 'O', 'O'},


{'X', 'X', 'O'},
{'X', 'X', 'O'},
{'O', 'O', 'X'},
{'O', 'O', 'X'},
{'X', 'X', 'O'}
};
Output: Number of islands is 3

mat[M][N] = {{'X', 'O', 'O', 'O', 'O', 'O'},


{'X', 'O', 'X', 'X', 'X', 'X'},
{'O', 'O', 'O', 'O', 'O', 'O'},
{'X', 'X', 'X', 'O', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'X'},
{'O', 'O', 'O', 'O', 'X', 'X'},
};
Output: Number of islands is 4

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++

// A C++ program to count the number of rectangular


// islands where every island is separated by a line
#include<iostream>
using namespace std;
  
// Size of given matrix is M X N
#define M 6
#define N 3
  
// 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
int countIslands(int mat[][N])
{
    int count = 0; // Initialize result
  
    // Traverse the input matrix
    for (int i=0; i<M; i++)
    {
        for (int 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++;
            }
        }
    }
  

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

// A Java program to count the number of rectangular


// islands where every island is separated by a line
import java.io.*;
  
class islands 
{
    // 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
    static int countIslands(int mat[][], int m, int n)
    {
        // Initialize result
        int count = 0; 
  
        // Traverse the input matrix
        for (int i=0; i<m; i++)
        {
            for (int 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'))

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#

// A C# program to count the number of rectangular 


// islands where every island is separated by 
// a line
using System;
  
class GFG {
      
    // 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
    static int countIslands(int [,]mat, int m, int n)
    {
          
        // Initialize result
        int count = 0; 
  

341
Chapter 48. Count number of islands where every island is row-wise and column-wise
separated

        // Traverse the input matrix


        for (int i = 0; i < m; i++)
        {
            for (int 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 program
    public static void Main () 
    {
          
        // 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'}
                    };
        Console.WriteLine("Number of rectangular "
         + "islands is: " + countIslands(mat, m, n));
    }
}
  
// This code is contributed by Sam007.

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

    echo "Number of rectangular islands is "


                       , countIslands($mat);
                         
// This code is contributed by nitin mittal
?>

Output:

Number of rectangular islands is 3

Time complexity of this solution is O(MN).


Improved By : Sam007, nitin mittal

Source

https://www.geeksforgeeks.org/count-number-islands-every-island-separated-line/

344
Chapter 49

Count number of squares in a


rectangle

Count number of squares in a rectangle - GeeksforGeeks


Given a m x n rectangle, how many squares are there in it?
Examples :

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

Let us first solve this problem for m = n, i.e., for a square:


For m = n = 1, output: 1
For m = n = 2, output: 4 + 1 [4 of size 1×1 + 1 of size 2×2]
For m = n = 3, output: 9 + 4 + 1 [4 of size 1×1 + 4 of size 2×2 + 1 of size 3×3]
For m = n = 4, output 16 + 9 + 4 + 1 [16 of size 1×1 + 9 of size 2×2 + 4 of size 3×3 + 1
of size 4×4]
In general, it seems to be n^2 + (n-1)^2 + … 1 = n(n+1)(2n+1)/6
Let us solve this problem when m may not be equal to n:
Let us assume that m <= n
From above explanation, we know that number of squares in a m x m matrix is
m(m+1)(2m+1)/6
What happens when we add a column, i.e., what is the number of squares in m x (m+1)
matrix?
When we add a column, number of squares increased is m + (m-1) + … + 3 + 2 + 1
[m squares of size 1×1 + (m-1) squares of size 2×2 + … + 1 square of size m x m]
Which is equal to m(m+1)/2
So when we add (n-m) columns, total number of squares increased is (n-m)*m(m+1)/2.
So total number of squares is m(m+1)(2m+1)/6 + (n-m)*m(m+1)/2.
Using same logic we can prove when n <= m.
So, in general,

Total number of squares = m x (m+1) x (2m+1)/6 +

346
Chapter 49. Count number of squares in a rectangle

(n-m) x m x (m+1)/2

when n is larger dimension

.
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

// C++ program to count squares 


// in a rectangle of size m x n
#include<iostream>
using namespace std;
  
// Returns count of all squares 
// in a rectangle of size m x n
int countSquares(int m, int n)
{
// If n is smaller, swap m and n
if (n < m)
    swap(m, n);
  
// Now n is greater dimension, 
// apply formula
return m * (m + 1) * (2 * m + 1) / 
     6 + (n - m) * m *(m + 1) / 2;
}
  
// Driver Code
int main()
{
int m = 4, n = 3;
cout << "Count of squares is "
     << countSquares(m, n);
}

Java

// Java program to count squares


// in a rectangle of size m x n
  
class GFG
{
    // Returns count of all squares 

347
Chapter 49. Count number of squares in a rectangle

    // in a rectangle of size m x n


    static int countSquares(int m, 
                            int n)
    {
    // If n is smaller, swap m and n
    if (n < m)
    {
        // swap(m, n)
        int temp = m;
        m = n;
        n = temp;
    }
          
      
    // Now n is greater dimension, 
    // apply formula
    return m * (m + 1) * (2 * m + 1) / 
        6 + (n - m) * m * (m + 1) / 2;
    }
      
    // Driver Code
    public static void main(String[] args) 
    {
        int m = 4, n = 3;
        System.out.println("Count of squares is " + 
                            countSquares(m, n));
    }
}

C#

// C# program to count squares in a rectangle


// of size m x n
using System;
  
class GFG {
      
    // Returns count of all squares in a 
    // rectangle of size m x n
    static int countSquares(int m, int n)
    {
    // If n is smaller, swap m and n
    if (n < m)
    {
        // swap(m,n)
        int temp = m;
        m = n;
        n = temp;

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

Count number of ways to reach


destination in a Maze

Count number of ways to reach destination in a Maze - GeeksforGeeks


Given a maze with obstacles, count number of paths to reach rightmost-bottommost cell
from topmost-leftmost cell. A cell in given maze has value -1 if it is a blockage or dead end,
else 0.
From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only.
Examples:

Input: maze[R][C] = {{0, 0, 0, 0},


{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
Output: 4
There are four possible paths as shown in
below diagram.

This problem is an extension of below problem.


Backtracking | Set 2 (Rat in a Maze)
In this post a different solution is discussed that can be used to solve the above Rat in a
Maze problem also.
The idea is to modify the given grid[][] so that grid[i][j] contains count of paths to
reach (i, j) from (0, 0) if (i, j) is not a blockage, else grid[i][j] remains -1.

We can recursively compute grid[i][j] using below

351
Chapter 50. Count number of ways to reach destination in a Maze

formula and finally return grid[R-1][C-1]

// If current cell is a blockage


if (maze[i][j] == -1)
maze[i][j] = -1; // Do not change

// If we can reach maze[i][j] from maze[i-1][j]


// then increment count.
else 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.
else if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);

Below is the implementation of above idea.

C++

// C++ program to count number of paths in a maze


// with obstacles.
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
  
// Returns count of possible paths in a maze[R][C]
// from (0,0) to (R-1,C-1)
int countPaths(int maze[][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 (int 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;

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

// java program to count number of paths in a maze


// with obstacles.
import java.io.*;
  
class GFG 
{
    static int R = 4;
    static int C = 4;
      
    // Returns count of possible paths in 
    // a maze[R][C] from (0,0) to (R-1,C-1)
    static int countPaths(int maze[][])
    {
        // 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 (int 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 (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.

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#

// C# program to count number of paths in a maze


// with obstacles.
using System;
  
class GFG {
      
    static int R = 4;
    static int C = 4;
      
    // Returns count of possible paths in 
    // a maze[R][C] from (0,0) to (R-1,C-1)
    static int countPaths(int [,]maze)
    {
          
        // 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 (int 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 (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

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

// This code is contributed by nitin mittal.

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

        // 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($i = 1; $i < $R; $i++)
    {
        for($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
    $maze = array(array(0, 0, 0, 0),

359
Chapter 50. Count number of ways to reach destination in a Maze

                  array(0, -1, 0, 0),


                  array(-1, 0, 0, 0),
                  array(0, 0, 0, 0));
    echo countPaths($maze);
  
// This code is contributed by anuj_67.
?>

Output:

Time Complexity : O(R x C)


Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/count-number-ways-reach-destination-maze/

360
Chapter 51

Count of elements of an array


present in every row of NxM
matrix

Count of elements of an array present in every row of NxM matrix - GeeksforGeeks


Given N rows with M elements each and an array arr[] of L numbers, the task is to print
the count of elements of that array present in every row of the matrix.
Examples:

Input: {8 27 39 589 23
23 34 589 12 45
939 32 27 12 78
23 349 48 21 32},

arr[] = {589, 39, 27}

Output: 1st row - 3


2nd row - 1
3rd row - 1
4th row - 0
In 1st row, all three elements in array z[] are present
In 2nd row, only 589 in array z[] are present
In 3rd row, only 27 in array z[] are present
In 4th row, none of the elements are present.

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

Output: 1st row - 2


2nd row - 1

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:

// C++ program to print the count of


// elements present in the NxM matrix
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the count of
// elements present in the NxM matrix
void printCount(int a[][5], int n, int m, int z[], int l)
{
    // iterate in the n rows
    for (int i = 0; i < n; i++) {
        // map to mark elements in N-th row
        unordered_map<int, int> mp;
  
        // mark all elements in the n-th row
        for (int j = 0; j < m; j++)
            mp[a[i][j]] = 1;
  
        int count = 0;
  
        // check for occurence of all elements
        for (int j = 0; j < l; j++) {
            if (mp[z[j]])
                count += 1;
        }
  
        // print the occurence of all elements
        cout << "row" << i + 1 << " = " << count << endl;
    }
}
  
// Driver Code

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

Time Complexity: O(N*M)

Source

https://www.geeksforgeeks.org/count-of-elements-of-an-array-present-in-every-row-of-nxm-matrix/

363
Chapter 52

Count of number of given string


in 2D character array

Count of number of given string in 2D character array - GeeksforGeeks


Given a 2-Dimensional character array and a string, we need to find the given string in
2-dimensional character array such that individual characters can be present left to right,
right to left, top to down or down to top.
Examples:

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

We have discussed simpler problem to find if a word exists or not in a matrix.


To count all occurrences, we follow simple brute force approach. Traverse through each
character of the matrix and taking each character as start of the string to be found, try to
search in all the possible directions. Whenever, a word is found, increase the count, and
after traversing the matrix what ever will be the value of count will be number of times
string exists in character matrix.
Algorithm :
1- Traverse matrix character by character and take one character as string start
2- For each character find the string in all the four directions recursively
3- If a string found, we increase the count
4- When we are done with one character as start, we repeat the same process for the next
character
5- Calculate the sum of count for each character
6- Final count will be the answer
C

// C code for finding count


// of string in a given 2D
// character array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
  
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))
  
// utility function to search
// complete string from any
// given index of 2d char array
int internalSearch(char *needle, int row,
                   int col, char **hay, 
                   int row_max, int col_max)
{
    int found = 0;
  
    if (row >= 0 && row <= row_max && col >= 0 &&
        col <= col_max && *needle == hay[row][col])
        {
              
        char match = *needle++;
  
        hay[row][col] = 0;
  
        if (*needle == 0) {
            found = 1;

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

Count of possible hexagonal


walks

Count of possible hexagonal walks - GeeksforGeeks


We are given an infinite two dimensional plane made of hexagons connected together. We
can visualize this plane as a honeycomb. Element X is present on one of the cells / hexagon.
We are given N steps, the task is to calculate number of such hexagonal paths possible in
which element X has to perform a walk of N steps and return back to the original hexagon,

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.

Below is the implementation of above approach :

C++

// C++ implementation of counting

369
Chapter 53. Count of possible hexagonal walks

// number of possible hexagonal walks


#include <iostream>
using namespace std;
  
int depth = 16;
int ways[16][16][16];
int stepNum;
  
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 according to the image.
    for (int N = 1; N <= 14; N++) 
    {
        for (int i = 1; i <= depth; i++) 
        {
            for (int j = 1; j <= depth; j++) 
            {
                ways[N][i][j] = ways[N - 1][i][j + 1] 
                                + ways[N - 1][i][j - 1]
                                + ways[N - 1][i + 1][j] 
                                + ways[N - 1][i - 1][j]
                                + ways[N - 1][i + 1][j - 1] 
                                + ways[N - 1][i - 1][j + 1];
            }
        }
  
        // This array stores the number of ways
        // possible for a given step
        list[N] = ways[N][8][8];
    }
}
  
// Driver function
int main()
{
    int list[15];
   
   // Preprocessing all possible ways
    preprocess(list);

370
Chapter 53. Count of possible hexagonal walks

    int steps = 4;
    cout << "Number of walks possible is/are " 
         << list[steps] << endl;
    return 0;
}

Java

// Java implementation of counting


// number of possible hexagonal walks
import java.util.*;
  
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 
        // according to the image.
        for (int N = 1; N <= 14; N++) 
        {
            for (int i = 1; i < depth; i++) 
            {
                for (int j = 1; j < depth; j++) 
                {
                    ways[N][i][j] = 
                            ways[N - 1][i][j + 1] 
                          + ways[N - 1][i][j - 1]
                          + ways[N - 1][i + 1][j] 
                          + ways[N - 1][i - 1][j]
                      + ways[N - 1][i + 1][j - 1] 
                     + ways[N - 1][i - 1][j + 1];
                }
            }

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

        // according to the image.


        for (int N = 1; N <= 14; N++) 
        {
            for (int i = 1; i < depth; i++) 
            {
                for (int j = 1; j < depth; j++) 
                {
                    ways[N,i,j] = 
                            ways[N - 1,i,j + 1] 
                        + ways[N - 1,i,j - 1]
                        + ways[N - 1,i + 1,j] 
                        + ways[N - 1,i - 1,j]
                    + ways[N - 1,i + 1,j - 1] 
                    + ways[N - 1,i - 1,j + 1];
                }
            }
      
            // 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() 
    {
        int []list = new int[15];
          
            // Preprocessing all possible ways
            preprocess(list);
            int steps = 4;
            Console.WriteLine( "Number of walks"
                        + " possible is/are "+
                                list[steps] );
    }
}
  
// This code is contributed by anuj_67.

Output :

Number of walks possible is/are 90

The time complexity of the above code is and the space complexity is

373
Chapter 53. Count of possible hexagonal walks

also similar due to the 3D array used.


Improved By : vt_m

Source

https://www.geeksforgeeks.org/count-possible-hexagonal-walks/

374
Chapter 54

Count pairs from two sorted


matrices with given sum

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:

Input : mat1[][] = { {1, 5, 6},


{8, 10, 11},
{15, 16, 18} }

mat2[][] = { {2, 4, 7},


{9, 10, 12},
{13, 16, 20} }
x = 21
Output : 4
The pairs are:
(1, 20), (5, 16), (8, 13) and (11, 10).

Method 1 (Naive Approach): For each element ele of mat1[][] linearly search (x – ele)
in mat2[][].
C++

// C++ implementation to count pairs from two 

375
Chapter 54. Count pairs from two sorted matrices with given sum

// sorted matrices whose sum is equal to a 


// given value x
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 10
  
// function to search 'val' in mat[][]
// returns true if 'val' is present
// else false
bool valuePresent(int mat[][SIZE], int n, int val)
{
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            if (mat[i][j] == val)
  
                // 'val' found
                return true;
  
    // 'val' not found
    return false;
}
  
// 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 (valuePresent(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 } };

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

// java implementation to count 


// pairs from twosorted matrices 
// whose sum is equal to a given value
import java.io.*;
  
class GFG
{    
    int SIZE= 10;
      
    // function to search 'val' in mat[][]
    // returns true if 'val' is present
    // else false
    static boolean valuePresent(int mat[][], int n, 
                                            int val)
    {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (mat[i][j] == val)
                      
                    // 'val' found
                    return true;
      
        // 'val' not found
        return false;
    }
      
    // 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)
    {

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

# Python3 implementation to count pairs


# from two sorted matrices whose sum is
# equal to a given value x 
  
# function to search 'val' in mat[][] 
# returns true if 'val' is present else
# false
def valuePresent(mat, n, val):
  
    for i in range(0, n):

378
Chapter 54. Count pairs from two sorted matrices with given sum

        for j in range(0, n):


  
            if mat[i][j] == val:
  
                # 'val' found
                return True
  
    # 'val' not found
    return False
  
# function to count pairs from two sorted
# matrices whose sum is equal to a given
# value x
def countPairs(mat1, mat2, n, x):
  
    count = 0
  
    for i in range(0, n):
        for j in range(0, n):
  
            # if value (x-mat1[i][j]) is found
            # in mat2[][]
            if valuePresent(mat2, n, x - mat1[i][j]):
                count += 1
  
    # required count of pairs
    return count
  
# Driver program
mat1 = [[ 1, 5, 6 ],
        [ 8, 10, 11 ],
        [ 15, 16, 18 ] ]
  
mat2 = [ [ 2, 4, 7 ],
         [ 9, 10, 12 ],
         [ 13, 16, 20 ] ]
  
n = 3
x = 21
  
print( "Count = "),
print(countPairs(mat1, mat2, n, x))
  
# This code is contributed by upendra bartwal

C#

//C# implementation to count 

379
Chapter 54. Count pairs from two sorted matrices with given sum

// pairs from twosorted matrices 


// whose sum is equal to a given value
using System;
  
class GFG

    // int SIZE= 10;
      
    // function to search 'val' in mat[][]
    // returns true if 'val' is present
    // else false
    static bool valuePresent(int[,] mat, int n, 
                                        int val)
    {
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (mat[i, j] == val)
                      
                    // 'val' found
                    return true;
      
        // 'val' not found
        return false;
    }
      
    // 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;
      
        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 () 
    {

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

Time Complexity: O(n4 ).


Auxiliary Space: O(1).
Method 2 (Binary Search): As matrix is strictly sorted, use the concept of binary
search technique. For each element ele of mat1[][] apply the binary search technique on the
elements of the first column of mat2[][] to find the row index number of the largest element
smaller than equal to (x – ele). Let it be row_no. If no such row exists then no pair
can be formed with element ele. Else apply the concept of binary search technique to find
the value (x – ele) in the row represented by row_no in mat2[][]. If value found then
increment count.
C++

// C++ implementation to count pairs from two


// sorted matrices whose sum is equal to a given
// value x
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 10
  
// function returns the row index no of largest
// element smaller than equal to 'x' in first

381
Chapter 54. Count pairs from two sorted matrices with given sum

// column of mat[][]. If no such element exists 


// then it returns -1.
int binarySearchOnRow(int mat[SIZE][SIZE],
                      int l, int h, int x)
{
    while (l <= h) {
        int 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
    return h;
}
  
// function to search 'val' in mat[row][]
bool binarySearchOnCol(int mat[][SIZE], int l, int h,
                       int val, int row)
{
    while (l <= h) {
        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

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

    cout << "Count = "


         << countPairs(mat1, mat2, n, x);
  
    return 0;
}

Java

// java implementation to count 


// pairs from two sorted matrices 
// whose sum is equal to a given
// value x
import java.io.*;
  
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 
    // then it returns -1.
    static int binarySearchOnRow(int mat[][], int l,
                                       int h, int x)
    {
        while (l <= h)
        {
            int 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
        return h;
    }
      
    // function to search 'val' in mat[row][]
    static boolean binarySearchOnCol(int mat[][], int l, int h,
                                             int val, int row)
    {
        while (l <= h)

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

        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 
    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 code is contributed by vt_m

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

    // then it returns -1.


    static int binarySearchOnRow(int [,]mat, int l,
                                    int h, int x)
    {
        while (l <= h)
        {
            int 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
        return h;
    }
      
    // function to search 'val' in mat[row][]
    static bool binarySearchOnCol(int [,]mat, int l, int h,
                                            int val, int row)
    {
        while (l <= h)
        {
            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;
    }
      

387
Chapter 54. Count pairs from two sorted matrices with given sum

    // function to search 'val' in mat[][]


    // returns true if 'val' is present
    // else false
    static bool 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;
      
        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 
    public static void Main () 
    {
        int [,]mat1 = { { 1, 5, 6 },
                        { 8, 10, 11 },
                        { 15, 16, 18 } };
  
        int [,]mat2 = { { 2, 4, 7 },
                        { 9, 10, 12 },

388
Chapter 54. Count pairs from two sorted matrices with given sum

                        { 13, 16, 20 } };


      
        int n = 3;
        int x = 21;
      
        Console.WriteLine ( "Count = " +
                        countPairs(mat1, mat2, n, x));
              
    }
}
  
// This code is contributed by vt_m

Output:

Count = 4

Time Complexity: (n2 log2 n).


Auxiliary Space: O(1).
Method 3 (Hashing): Create a hash table and insert all the elements of mat2[][] in it.
Now for each element ele of mat1[][] find (x – ele) in the hash table.

// C++ implementation to count pairs from two


// sorted matrices whose sum is equal to a 
// given value x
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 10
  
// 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;
  
    // unordered_set 'us' implemented as hash table
    unordered_set<int> us;
  
    // insert all the elements of mat2[][] in 'us'
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            us.insert(mat2[i][j]);
  

389
Chapter 54. Count pairs from two sorted matrices with given sum

    // for each element of mat1[][]


    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
  
            // if (x-mat1[i][j]) is in 'us'
            if (us.find(x - mat1[i][j]) != us.end())
                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;
  
    cout << "Count = "
         << countPairs(mat1, mat2, n, x);
  
    return 0;
}

Output:

Count = 4

Time complexity: O(n2 ).


Auxiliary Space: O(n2 ).
Method 4 (Efficient Approach): From the top leftmost element traverse mat1[][] in
forward direction (i.e., from the topmost row up to last, each row is being traversed from
left to right) and from the bottom rightmost element traverse mat2[][] in backward direction
(i.e, from the bottom row up to first, each row is being traversed from right to left). For
each element e1 of mat1[][] and e2 of mat2[][] encountered, calculate val = (e1 + e2). If
val == x, increment count. Else if val is less than x, move to next element of mat1[][] in
forward direction. Else move to next element of mat2[][] in backward direction. Continue

390
Chapter 54. Count pairs from two sorted matrices with given sum

this process until either of the two matrices gets completely traversed.

C++

// C++ implementation to count pairs from two 


// sorted matrices whose sum is equal to a
// given value x
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 10
  
// 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)
{
    // 'r1' and 'c1' for pointing current element
    // of mat1[][]
    // 'r2' and 'c2' for pointing current element
    // of mat2[][]
    int r1 = 0, c1 = 0;
    int r2 = n - 1, c2 = n - 1;
  
    // while there are more elements
    // in both the matrices
    int count = 0;
    while ((r1 < n) && (r2 >= -1)) {
        int val = mat1[r1][c1] + mat2[r2][c2];
  
        // if true
        if (val == x) {
  
            // increment 'count'
            count++;
  
            // move mat1[][] column 'c1' to right
            // move mat2[][] column 'c2' to left
            c1++;
            c2--;
        }
  
        // if true, move mat1[][] column 'c1' to right
        else if (val < x)
            c1++;
  
        // else move mat2[][] column 'c2' to left

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

// java implementation to count 


// pairs from two  sorted 
// matrices whose sum is 
// equal to agiven value x
import java.io.*;
  
class GFG 
{
    int SIZE = 10;
      
    // 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)
    {
        // 'r1' and 'c1' for pointing current 
        // element of mat1[][]
        // 'r2' and 'c2' for pointing current 
        // element of mat2[][]
        int r1 = 0, c1 = 0;
        int r2 = n - 1, c2 = n - 1;
      
        // while there are more elements
        // in both the matrices
        int count = 0;
        while ((r1 < n) && (r2 >= -1)) 
        {
            int val = mat1[r1][c1] + mat2[r2][c2];
      
            // if true
            if (val == x) {
      
                // increment 'count'
                count++;
      
                // move mat1[][] column 'c1' to right
                // move mat2[][] column 'c2' to left
                c1++;
                c2--;
            }
      
            // if true, move mat1[][] 
            // column 'c1' to right
            else if (val < x)
                c1++;

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#

// C# implementation to count pairs


// from two sorted matrices whose 
// sum is equal to a given value x
using System;
  
class GFG {
  
    // 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)
    {
          
        // 'r1' and 'c1' for pointing
        // current element of mat1[][]
        // 'r2' and 'c2' for pointing
        // current element of mat2[][]
        int r1 = 0, c1 = 0;
        int r2 = n - 1, c2 = n - 1;
      
        // while there are more elements
        // in both the matrices
        int count = 0;
        while ((r1 < n) && (r2 >= -1)) 
        {
            int val = mat1[r1,c1] 
                          + mat2[r2,c2];
      
            // if true
            if (val == x) {
      
                // increment 'count'
                count++;
      
                // move mat1[][] column 
                // 'c1' to right
                // move mat2[][] column 
                // 'c2' to left
                c1++;
                c2--;

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

                        { 13, 16, 20 } };


      
        int n = 3;
        int x = 21;
      
        Console.Write ( "Count = " + 
            countPairs(mat1, mat2, n, x));
              
    }
}
  
// This code is contributed by 
// nitin mittal

Output:

Count = 4

Time Complexity: O(n2 ).


Auxiliary Space: O(1).
Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/count-pairs-two-sorted-matrices-given-sum/

397
Chapter 55

Count rows/columns with sum


equals to diagonal sum

Count rows/columns with sum equals to diagonal sum - GeeksforGeeks


Given an n x n square matrix, count all rows and columns whose sum is equal to the sum
of any principal diagonal or secondary diagonal.
Examples:

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

// C++ program to Count number of rows and


// columns having sum is equal to sum of 
// any diagonal in matrix
#include <iostream>
#define n 4
using namespace std;
  
  
// function to count number of rows countnd columns
// whose sum is equal to sum of any diagonal
int count(int arr[][n])
{
    int diag1 = 0, diag2 = 0;
    int row = 0, col = 0, count = 0;
  
    for (int 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 (int i = 0; i < n; i++) {
        row = 0, col = 0;
          
        for (int j = 0; j < n; j++) {
            row = row + arr[i][j];
        }
        for (int j = 0; j < n; j++) {
            col = col + arr[j][i];
        }
        if ((row == diag1) || (row == diag2)) {
            count++;
        }
        if ((col == diag1) || (col == diag2))
            count++;
    }
      
    return count;
}
  
// Driver code
int main()
{

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

// Java program to Count number of rows and


// columns having sum is equal to sum of
// any diagonal in matrix
  
import java.io.*;
  
class GFG {
  
    static int n = 4;
      
    // function to count number of rows countnd 
    // columns whose sum is equal to sum of any
    // diagonal
    static int count(int arr[][])
    {
          
        int diag1 = 0, diag2 = 0;
        int row = 0, col = 0, count = 0;
  
        for (int 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 (int i = 0; i < n; i++) {
            row = 0;
            col = 0;
  
            for (int j = 0; j < n; j++) {
                row = row + arr[i][j];
            }
              

400
Chapter 55. Count rows/columns with sum equals to diagonal sum

            for (int j = 0; j < n; j++) {


                col = col + arr[j][i];
            }
              
            if ((row == diag1) || (row == diag2)) 
                count++;
              
            if ((col == diag1) || (col == diag2))
                count++;
        }
  
        return count;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr[][] = {{7, 2, 3, 5},
                        {4, 5, 6, 3},
                        {7, 9, 10, 12},
                        {1, 5, 4, 3}};
                          
        System.out.println(count(arr));
    }
}
  
// This code is contributed by vt_m.

Python3

# Python3 program to Count number of rows 


# and columns having sum is equal to sum  
# of any diagonal in matrix
n = 4
  
# Function to count number of rows
# countnd columns whose sum is equal
# to sum of any diagonal
def count(arr):
    diag1 = 0; diag2 = 0; row = 0
    col = 0; count = 0; j = n - 1
      
    for i in range(n):
      
        # sum of principle diagonal
        diag1 += arr[i][i]
  
        # sum of secondary diagonal

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#

// C# program to Count number of rows and


// columns having sum is equal to sum of
// any diagonal in matrix
using System;
  
namespace Matrix
{
public class GFG
{     
      
static int n = 4;
      
    // Function to count number of rows  

402
Chapter 55. Count rows/columns with sum equals to diagonal sum

    // countnd columns whose sum is equal 


    // to sum of any diagonal
    static int count(int [,]arr)
    {
          
        int diag1 = 0, diag2 = 0;
        int row = 0, col = 0, count = 0;
  
        for (int 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 (int i = 0; i < n; i++) {
            row = 0;
            col = 0;
  
            for (int j = 0; j < n; j++) {
                row = row + arr[i,j];
            }
              
            for (int j = 0; j < n; j++) {
                col = col + arr[j,i];
            }
              
            if ((row == diag1) || (row == diag2)) 
                count++;
              
            if ((col == diag1) || (col == diag2))
                count++;
        }
  
        return count;
    }
  
  
    // Driver code
    public static void Main()
    {
        int [,]arr = {  { 7, 2, 3, 5 },
                        { 4, 5, 6, 3 },

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:

Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/count-rowscolumns-with-sum-equals-to-diagonal-sum/

405
Chapter 56

Count sub-matrices having sum


divisible ‘k’

Count sub-matrices having sum divisible ’k’ - GeeksforGeeks


Given a n x n matrix of integers and a positive integer k. The problem is to count all
sub-matrices having sum divisible by the given value k.
Examples:

Input : mat[][] = { {5, -1, 6},


{-2, 3, 8},
{7, 4, -9} }

k = 4

Output : 6
The index range for the sub-matrices are:
(0, 0) to (0, 1)
(1, 0) to (2, 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++

// C++ implementation to count sub-matrices having sum


// divisible by the value 'k'
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 10
  
// function to count all sub-arrays divisible by k
int subCount(int arr[], int n, int k)
{
    // create auxiliary hash array to count frequency
    // of remainders
    int mod[k];
    memset(mod, 0, sizeof(mod));
  
    // 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];
  
        // as the sum can be negative, taking modulo
        // twice
        mod[((cumSum % k) + k) % k]++;
    }
  
    int result = 0; // Initialize result
  
    // 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];

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’

    cout << "Count = "


         << countSubmatrix(mat, n, k);
    return 0;
}

Java

// Java implementation to count 


// sub-matrices having sum
// divisible by the value 'k'
import java.util.*;
  
class GFG {
      
static final int SIZE = 10;
  
// 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];
    Arrays.fill(mod, 0);
  
    // 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];
  
    // 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;

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’

    int mat[][] = {{5, -1, 6}, 


                   {-2, 3, 8}, 
                   {7, 4, -9}};
    int n = 3, k = 4;
    System.out.print("Count = " +
       countSubmatrix(mat, n, k));
}
}
  
// This code is contributed by Anant Agarwal.

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’

    // create auxiliary hash 


    // array to count frequency 
    // of remainders
    $mod = array();
    for($i = 0; $i < $k; $i++)
        $mod[$i] = 0;
  
    // 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 = 0; $i < $n; $i++)
    {
        $cumSum += $arr[$i];
  
        // as the sum can be 
        // negative, taking 
        // modulo twice
        $mod[(($cumSum % $k) + 
               $k) % $k]++;
    }
  
    $result = 0; // Initialize result
  
    // Traverse mod
    for ($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

416
Chapter 56. Count sub-matrices having sum divisible ‘k’

// divisible by the value 'k'


function countSubmatrix($mat, $n, $k)
{
    // Variable to store 
    // the final output
    $tot_count = 0;
  
    $temp = array(); 
  
    // Set the left column
    for ($left = 0; 
         $left < $n; $left++)
    {
  
        // Initialize all 
        // elements of temp as 0
        for($i = 0; $i < $n; $i++)
            $temp[$i] = 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
$mat = array(array(5, -1, 6),

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

Time Complexity: O(n^3).


Auxiliary Space: O(n).
Improved By : manishshaw1

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

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++

// C++ program to count number of 0s in the given


// row-wise and column-wise sorted binary matrix.
#include <iostream>
using namespace std;
// define size of square matrix
#define N 5
  
// Function to count number of 0s in the given
// row-wise and column-wise sorted binary matrix.
int countZeroes(int mat[N][N])
{
    // 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])
  
            // 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++;

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

// Java program to count number of 0s in the given


// row-wise and column-wise sorted binary matrix
import java.io.*;
  
class GFG 
{
    public static int N = 5;
      
    // 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,

421
Chapter 57. Count zeros in a row wise and column wise sorted matrix

                // 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 program
    public static void main (String[] args) 
    {
        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 } };
        System.out.println(countZeroes(mat));
    }
}
  
// This code is contributed by Pramod Kumar

Python

# Python 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.
def countZeroes(mat):
      
    # start from bottom-left
    # corner of the matrix
    N = 5;
    row = N - 1;
    col = 0;
  
    # stores number of 

422
Chapter 57. Count zeros in a row wise and column wise sorted matrix

    # 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;
            row = row - 1;
  
        # add 0s present in
        # current column to result
        count = count + (row + 1);
  
        # move right to
        # next column
        col = col + 1;
  
    return count;
      
# Driver Code
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]];
  
print( countZeroes(mat));
  
# This code is contributed
# by chandan_jnu 

C#

// C# program to count number of


// 0s in the given row-wise and
// column-wise sorted binary matrix
using System;
  
class GFG 
{
    public static int N = 5;

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

// This code is contributed by KRV.

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

Counting sets of 1s and 0s in a


binary matrix

Counting sets of 1s and 0s in a binary matrix - GeeksforGeeks


Given a n × m binary matrix, count the number of sets where a set can be formed one or
more same values in a row or column.
Examples:

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

The number of non-empty subsets of x elements is 2x – 1. We traverse every row and


calculate numbers of 1’s and 0’s cells. For every u zeros and v ones, total sets is 2u – 1 +
2v – 1. We then traverse all columns and compute same values and compute overall sum.
We finally subtract m x n from the overall sum as single elements are considered twice.
CPP

// CPP program to compute number of sets

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

// Java program to compute number of sets


// in a binary matrix.
class GFG {
static final int m = 3; // no of columns
static final int n = 2; // no of rows
  
// function to calculate the number of
// non empty sets of cell
static long countSets(int a[][]) {
  
    // stores the final answer
    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++) {
        if (a[i][j] == 1)
        u++;
        else
        v++;
    }
    res += Math.pow(2, u) - 1 + Math.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++) {
        if (a[j][i] == 1)
        u++;
        else
        v++;
    }
    res += 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(String[] args) {
    int a[][] = {{1, 0, 1}, {0, 1, 0}};
  

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#

// C# program to compute number of


// sets in a binary matrix.
using System;
  
class GFG {
      
    static int m = 3; // no of columns
    static int n = 2; // no of rows
      
    // function to calculate the number of
    // non empty sets of cell
    static long countSets(int [,]a)
    {
      
        // stores the final answer
        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++)
            {
                if (a[i,j] == 1)
                    u++;
                else
                    v++;
            }
            res += (long)(Math.Pow(2, u) - 1
                       + Math.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++)
            {
                if (a[j,i] == 1)

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:

Time Complexity: O(n * m)


Improved By : vt_m

Source

https://www.geeksforgeeks.org/counting-sets-of-1s-and-0s-in-a-binary-matrix/

432
Chapter 59

Counts paths from a point to


reach Origin

Counts paths from a point to reach Origin - GeeksforGeeks


You are standing on a point (n, m) and you want to go to origin (0, 0) by taking steps
either left or down i.e. from each point you are allowed to move either in (n-1, m) or (n,
m-1). Find the number of paths from point to origin.
Examples:

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.

// Recursive function to count number of paths


countPaths(n, m)
{
// If we reach bottom or top left, we are
// have only one way to reach (0, 0)
if (n==0 || m==0)
return 1;

434
Chapter 59. Counts paths from a point to reach Origin

// Else count sum of both ways


return (countPaths(n-1, m) + countPaths(n, m-1));
}

Below is C++ implementation of above steps.

C++

// CPP program to count total number of


// paths from a point to origin
#include<bits/stdc++.h>
using namespace std;
  
// Recursive function to count number of paths
int countPaths(int n, int m)
{
    // If we reach bottom or top left, we are
    // have only one way to reach (0, 0)
    if (n==0 || m==0)
        return 1;
  
    // Else count sum of both ways
    return (countPaths(n-1, m) + countPaths(n, m-1));
}
  
// Driver Code
int main()
{
    int n = 3, m = 2;
    cout << " Number of Paths " << countPaths(n, m);
    return 0;
}

Java

// Java program to count total number of


// paths from a point to origin
import java.io.*;
  
class GFG {
      
    // Recursive function to count number of paths
    static int countPaths(int n, int m)
    {
        // If we reach bottom or top left, we are
        // have only one way to reach (0, 0)
        if (n == 0 || m == 0)

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

# Python program to count


# total number of
# paths from a point to origin
# Recursive function to 
# count number of paths
def countPaths(n,m):
  
    # If we reach bottom
    # or top left, we are
    # have only one way to reach (0, 0)
    if (n==0 or m==0):
        return 1
   
    # Else count sum of both ways
    return (countPaths(n-1, m) + countPaths(n, m-1))
  
# Driver Code
n = 3
m = 2
print(" Number of Paths ", countPaths(n, m))
  
# This code is contributed
# by Azkia Anam.

C#

// C# program to count total number of

436
Chapter 59. Counts paths from a point to reach Origin

// paths from a point to origin


using System;
          
public class GFG {
      
    // Recursive function to count number
    // of paths
    static int countPaths(int n, int m)
    {
          
        // If we reach bottom or top left,
        // we are have only one way to
        // reach (0, 0)
        if (n == 0 || m == 0)
            return 1;
      
        // Else count sum of both ways
        return (countPaths(n - 1, m) 
                 + countPaths(n, m - 1));
    }
      
    // Driver Code
    public static void Main ()
    {
        int n = 3, m = 2;
          
        Console.WriteLine (" Number of"
         + " Paths " + countPaths(n, m));
          
    }
}
  
// This code is contributed by Sam007.

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

    // reach (0, 0)


    if ($n == 0 || $m == 0)
        return 1;
  
    // Else count sum of both ways
    return (countPaths($n - 1, $m) + 
            countPaths($n, $m - 1));
}
  
    // Driver Code
    $n = 3; 
    $m = 2;
    echo " Number of Paths " 
      , countPaths($n, $m);
  
// This code is contributed by aj_36
?>

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++

// CPP program to count total number of


// paths from a point to origin
#include<bits/stdc++.h>
using namespace std;
  
// DP based function to count number of paths
int countPaths(int n, int m)
{
    int dp[n+1][m+1];
  
    // Fill entries in bottommost row and leftmost
    // columns
    for (int i=0; i<=n; i++)
      dp[i][0] = 1;
    for (int i=0; i<=m; i++)
      dp[0][i] = 1;
  
    // Fill DP in bottom up manner
    for (int i=1; i<=n; i++)

438
Chapter 59. Counts paths from a point to reach Origin

       for (int j=1; j<=m; j++)


          dp[i][j] = dp[i-1][j] + dp[i][j-1];
  
    return dp[n][m];
}
  
// Driver Code
int main()
{
    int n = 3, m = 2;
    cout << " Number of Paths " << countPaths(n, m);
    return 0;
}

Java

// Java program to count total number of


// paths from a point to origin
import java.io.*;
  
class GFG {
      
    // DP based function to count number of paths
    static int countPaths(int n, int m)
    {
        int dp[][] = new int[n + 1][m + 1];
      
        // Fill entries in bottommost row and leftmost
        // columns
        for (int i = 0; i <= n; i++)
            dp[i][0] = 1;
        for (int i = 0; i <= m; i++)
            dp[0][i] = 1;
      
        // Fill DP in bottom up manner
        for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
      
        return dp[n][m];
    }
      
    // Driver Code
    public static void main (String[] args) {
        int n = 3, m = 2;
        System.out.println(" Number of Paths "
                           + countPaths(n, m));
          

439
Chapter 59. Counts paths from a point to reach Origin

    }
}
  
// This code is contributed by vt_m

C#

// C# program to count total number of


// paths from a point to origin
using System;
          
public class GFG {
      
    // DP based function to count number
    // of paths
    static int countPaths(int n, int m)
    {
        int [,]dp = new int[n + 1,m + 1];
      
        // Fill entries in bottommost row
        // and leftmost columns
        for (int i = 0; i <= n; i++)
            dp[i,0] = 1;
        for (int i = 0; i <= m; i++)
            dp[0,i] = 1;
      
        // Fill DP in bottom up manner
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                dp[i,j] = dp[i - 1,j]
                         + dp[i,j - 1];
          
        return dp[n,m];
    }
      
    // Driver Code
    public static void Main ()
    {
        int n = 3, m = 2;
          
        Console.WriteLine(" Number of"
        + " Paths " + countPaths(n, m));
          
    }
}
  
// This code is contributed by Sam007.

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

Improved By : Sam007, jit_t

Source

https://www.geeksforgeeks.org/counts-paths-point-reach-origin/

441
Chapter 60

Create a matrix with


alternating rectangles of O and
X

Create a matrix with alternating rectangles of O and X - GeeksforGeeks


Write a code which inputs two numbers m and n and creates a matrix of size m x n (m
rows and n columns) in which every elements is either X or 0. The Xs and 0s must be filled
alternatively, the matrix should have outermost rectangle of Xs, then a rectangle of 0s, then
a rectangle of Xs, and so on.
Examples:

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

// Java code to demonstrate the working.


  
import java.io.*;
  
class GFG {
  
// Function to print alternating
// rectangles of 0 and X
 static 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[][] = new char[m][n];
  
        // Iniitialize the character
        // to be stoed in a[][]
    char 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 the remaining columns */
        for (i = k; i < m; ++i)
            a[i][n-1] = x;

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#

// C# code to demonstrate the working.


using System;
  
class GFG {
  
    // Function to print alternating
    // rectangles of 0 and X
    static 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 = new char[m,n];
      
        // Iniitialize the character
        // to be stoed in a[][]
        char 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 the
            remaining columns */
            for (i = k; i < m; ++i)
                a[i,n-1] = x;
            n--;

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

           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 ($j = 0; $j < $c; $j++)
            echo($a[$i][$j]." ");
        echo "\n";
    }
}
  
// Driver Code
echo "Output for m = 5, n = 6\n";
fill0X(5, 6);
  
echo "\nOutput for m = 4, n = 4\n";
fill0X(4, 4);
  
echo "\nOutput for m = 3, n = 4\n";
fill0X(3, 4);
  
// This code is contributed by ChitraNayal.

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

Time Complexity: O(mn)


Auxiliary Space: O(mn)
Please suggest if someone has a better solution which is more efficient in terms of space and
time.
This article is contributed by Deepak Bisht. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007, ChitraNayal

Source

https://www.geeksforgeeks.org/create-a-matrix-with-alternating-rectangles-of-0-and-x/

451
Chapter 61

Determinant of a Matrix

Determinant of a Matrix - GeeksforGeeks


What is Determinant of a Matrix?
Determinant of a Matrix is a special number that is defined only for square matrices (ma-
trices which have same number of rows and columns). Determinant is used at many places
in calculus and other matrix related algebra, it actually represents the matrix in term of a
real number which can be used in solving system of linear equation and finding the inverse
of a matrix.
How to calculate?
The value of determinant of a matrix can be calculated by following procedure –
For each element of first row or first column get cofactor of those elements and then multiply
the element with the determinant of the corresponding cofactor, and finally add them with
alternate signs. As a base case the value of determinant of a 1*1 matrix is the single value
itself.
Cofactor of an element, is a matrix which we can get by removing row and column of that
element from that matrix.
Determinant of 2 x 2 Matrix:

452
Chapter 61. Determinant of a Matrix

Determinant of 3 x 3 Matrix:

C++

// C++ program to find Deteminant of a matrix


#include <bits/stdc++.h>
using namespace std;
  
// Dimension of input square matrix
#define N 4
  
// Function to get cofactor of mat[p][q] in temp[][]. n is current
// dimension of mat[][]
void getCofactor(int mat[N][N], int temp[N][N], 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++)

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

// Java program to find Deteminant of 


// a matrix
class GFG {
      
    // Dimension of input square matrix
    static final 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 

455
Chapter 61. Determinant of a Matrix

        // 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
      
        // 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);

456
Chapter 61. Determinant of a Matrix

            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++)
                System.out.print(mat[i][j]);
                  
            System.out.print("\n");
        }
    }
      
    // Driver code
    public static void main (String[] args)
    {
          
        int mat[][] = {{1, 0, 2, -1},
                        {3, 0, 0, 5},
                        {2, 1, 4, -3},
                        {1, 0, 5, 0}};
      
        System.out.print("Determinant " + 
                    "of the matrix is : "+
             determinantOfMatrix(mat, N));
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program to find Deteminant of 


// a matrix
using System;
class GFG {
      
    // Dimension of input square matrix

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:

Determinant of the matrix is : 30

Adjoint and Inverse of a Matrix


There are various properties of the Determinant which can be helpful for solving problems
related with matrices,
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/determinant-of-a-matrix/

460
Chapter 62

Diagonally Dominant Matrix

Diagonally Dominant Matrix - GeeksforGeeks


In mathematics, a square matrix is said to be diagonally dominant if for every row of
the matrix, the magnitude of the diagonal entry in a row is larger than or equal to the sum
of the magnitudes of all the other (non-diagonal) entries in that row. More precisely, the
matrix A is diagonally dominant if

For example, The matrix

is diagonally dominant because


|a11 | � |a12 | + |a13 | since |+3| � |-2| + |+1|
|a22 | � |a21 | + |a23 | since |-3| � |+1| + |+2|
|a33 | � |a31 | + |a32 | since |+4| � |-1| + |+2|
Given a matrix A of n rows and n columns. The task is tho check whether matrix A is
diagonally dominant or not.
Examples :

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++

// CPP Program to check whether given matrix


// is Diagonally Dominant Matrix.
#include <bits/stdc++.h>
#define N 3
using namespace std;
  
// check the given given matrix is Diagonally
// Dominant Matrix or not.
bool isDDM(int m[N][N], int n)
{
    // for each row
    for (int i = 0; i < n; i++)
   {        
  
        // for each column, finding sum of each row.
        int sum = 0;
        for (int j = 0; j < n; j++)             
            sum += abs(m[i][j]);        
  
        // removing the diagonal element.
        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; 
         
    }

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

// JAVA Program to check whether given matrix


// is Diagonally Dominant Matrix.
import java.util.*;
  
class GFG {
      
    // check the given given matrix is Diagonally
    // Dominant Matrix or not.
    static boolean isDDM(int m[][], int n)
    {
        // for each row
        for (int i = 0; i < n; i++)
        {        
       
            // for each column, finding 
            //sum of each row.
            int sum = 0;
            for (int j = 0; j < n; j++)             
                sum += Math.abs(m[i][j]);        
       
            // removing the diagonal element.
            sum -= Math.abs(m[i][i]);
       
            // checking if diagonal element is less 
            // than sum of non-diagonal element.
            if (Math.abs(m[i][i]) < sum) 
                return false; 
         
        }

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

# Python Program to check


# whether given matrix is 
# Diagonally Dominant Matrix.
  
# check the given given 
# matrix is Diagonally 
# Dominant Matrix or not.
def isDDM(m, n) :
  
    # for each row
    for i in range(0, n) :         
      
        # for each column, finding
        # sum of each row.
        sum = 0
        for j in range(0, n) :
            sum = sum + abs(m[i][j])     
  
        # removing the 
        # diagonal element.
        sum = sum - abs(m[i][i])
  
        # checking if diagonal 
        # element is less than 

464
Chapter 62. Diagonally Dominant Matrix

        # sum of non-diagonal


        # element.
        if (abs(m[i][i]) < sum) :
            return False
  
    return True
  
# Driver Code
n = 3
m = [[ 3, -2, 1 ],
    [ 1, -3, 2 ],
    [ -1, 2, 4 ]]
  
if((isDDM(m, n))) :
    print ("YES")
else :
    print ("NO")
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# Program to check whether given matrix


// is Diagonally Dominant Matrix.
using System;
  
class GFG {
      
    // check the given given matrix is Diagonally
    // Dominant Matrix or not.
    static bool isDDM(int [,]m, int n)
    {
        // for each row
        for (int i = 0; i < n; i++)
        { 
      
            // for each column, finding 
            //sum of each row.
            int sum = 0;
            for (int j = 0; j < n; j++)         
                sum += Math.Abs(m[i, j]);     
      
            // removing the diagonal element.
            sum -= Math.Abs(m[i, i]);
      
            // checking if diagonal element is less 
            // than sum of non-diagonal element.

465
Chapter 62. Diagonally Dominant Matrix

            if (Math.Abs(m[i,i]) < sum) 


                return false; 
          
        }
  
        return true;
    }
  
    // Driver program 
    public static void Main() 
    {
        int n = 3;
        int [,]m = { { 3, -2, 1 },
                    { 1, -3, 2 },
                    { -1, 2, 4 } };
      
        if (isDDM(m, n))
            Console.WriteLine("YES") ;
        else
            Console.WriteLine("NO");
      
    }
}
  
// This code is contributed by Vt_m.

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

Improved By : SanjuTomar, manishshaw1

Source

https://www.geeksforgeeks.org/diagonally-dominant-matrix/

467
Chapter 63

Different Operations on
Matrices

Different Operations on Matrices - GeeksforGeeks


For introduction on matrices, you can refer the following article: Matrix Introduction
In this article, we will discuss various operations on matrices and their properties:
Matrices Addition –
The addition of two matrices A m*n and Bm*n gives a matrix Cm*n . The elements of C are
sum of corresponding elements in A and B which can be shown as:

The algorithm for addition of matrices can be written as:

for i in 1 to m
for j in 1 to n
cij = aij + bij

Key points:

• Addition of matrices is commutative which means A+B = B+A


• Addition of matrices is associative which means A+(B+C) = (A+B)+C
• The order of matrices A, B and A+B is always same
• If order of A and B is different, A+B can’t be computed
• The complexity of addition operation is O(m*n) where m*n is order of matrices

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:

The algorithm for subtraction of matrices can be written as:

for i in 1 to m
for j in 1 to n
cij = aij-bij

Key points:

• Subtraction of matrices is non-commutative which means A-B � B-A


• Subtraction of matrices is non-associative which means A-(B-C) � (A-B)-C
• The order of matrices A, B and A-B is always same
• If order of A and B is different, A-B can’t be computed
• The complexity of subtraction operation is O(m*n) where m*n is order of matrices

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

• Multiplication of matrices is non-commutative which means A*B � B*A


• Multiplication of matrices is associative which means A*(B*C) = (A*B)*C
• For computing A*B, the number of columns in A must be equal to number of rows in
B
• Existence of A*B does not imply existence of B*A
• The complexity of multiplication operation (A*B) is O(m*n*p) where m*n and n*p
are order of A and B respectively
• The order of matrix C computed as A*B is O(m*p) where m*n and n*p are order of
A and B respectively

Read next – Determinant of a Matrix, Adjoint and Inverse of a Matrix


Improved By : RahulWankhede

Source

https://www.geeksforgeeks.org/different-operation-matrices/

470
Chapter 64

Direction at last square block

Direction at last square block - GeeksforGeeks


Given a R x C (1 <= R, C <= 1000000000) grid and initial position as top left corner and
direction as east. Now we start running in forward direction and cross each square blocks
of matrix. Whenever we find dead end or reach a cell that is already visited, we take right
because we can not cross the visited square blocks again. Tell the direction when we will be
at last square block.
For example : Consider the case with R = 3, C = 3. The path followed will be (0, 0) —
(0, 1) — (0, 2) — (1, 2) — (2, 2) — (2, 1) — (2, 0) — (1, 0) — (1, 1). At this point, all
squares have been visited, and is facing right.
Examples :

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

• If you are right coloumn, then your current direction is “Down”.


• If you are traversing bottom row, then your current direction is “Left”.
• If you are traversing left coloumn, then your current direction is “Up”.

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 :

1. R != C and R is even and C is odd and R<C, direction will be “Left”.


2. R != C and R is odd and C is even and R<C, direction will be “Right”.
3. R != C and R is even and C is even and R<C, direction will be “Left”.
4. R != C and R is odd and C is odd and R<C, direction will be “Right”.
5. R != C and R is even and C is odd and R>C, direction will be “Down”.
6. R != C and R is odd and C is even and R>C, direction will be “Up”.
7. R != C and R is even and C is even and R>C, direction will be “Up”.
8. R != C and R is odd and C is odd and R>C, direction will be “Down”.
9. R == C and R is even and C is even, direction will be “Left”.
10. R == C and R is odd and C is odd, direction will be “Right”.

Below is implementation of above idea.

C++

// C++ program to tell the Current direction in


// R x C grid
#include <iostream>
using namespace std;
typedef long long int ll;
  
// Function which tells the Current direction
void direction(ll R, ll C)
{
    if (R != C && R % 2 == 0 && C % 2 != 0 && R < C) {
        cout << "Left" << endl;
        return;
    }
    if (R != C && R % 2 != 0 && C % 2 == 0 && R > C) {
        cout << "Up" << endl;
        return;
    }
    if (R == C && R % 2 != 0 && C % 2 != 0) {

472
Chapter 64. Direction at last square block

        cout << "Right" << endl;


        return;
    }
    if (R == C && R % 2 == 0 && C % 2 == 0) {
        cout << "Left" << endl;
        return;
    }
    if (R != C && R % 2 != 0 && C % 2 != 0 && R < C) {
        cout << "Right" << endl;
        return;
    }
    if (R != C && R % 2 != 0 && C % 2 != 0 && R > C) {
        cout << "Down" << endl;
        return;
    }
    if (R != C && R % 2 == 0 && C % 2 == 0 && R < C) {
        cout << "Left" << endl;
        return;
    }
    if (R != C && R % 2 == 0 && C % 2 == 0 && R > C) {
        cout << "Up" << endl;
        return;
    }
    if (R != C && R % 2 == 0 && C % 2 != 0 && R > C) {
        cout << "Down" << endl;
        return;
    }
    if (R != C && R % 2 != 0 && C % 2 == 0 && R < C) {
        cout << "Right" << endl;
        return;
    }
}
  
// Driver program to test the Cases
int main()
{
    ll R = 3, C = 1;
    direction(R, C);
    return 0;
}

Java

// Java program to tell the Current direction in


// R x C grid
import java.io.*;
  
class GFG {

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#

// C# program to tell the Current


// direction in R x C grid
using System;
  
class GFG
{
      
    // Function which tells 
    // the Current direction 
    static void direction(int R, int C)
    {
        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) 
        {
            Console.WriteLine("Right");
            return;
        }
        if (R == C && R % 2 == 0 && 
            C % 2 == 0) 
        {
            Console.WriteLine("Left");
            return;
        }
        if (R != C && R % 2 != 0 &&
            C % 2 != 0 && R < 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

Time Complexity : O(1)


Auxiliary Space : O(1)
Reference: http://www.spoj.com/problems/TRGRID/
This article is contributed by Shashank Mishra (Gullu).This article is reviewd by team
GeeksforGeeks.
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

Source
https://www.geeksforgeeks.org/direction-last-square-block/

478
Chapter 65

Discrete Cosine Transform


(Algorithm and Program)

Discrete Cosine Transform (Algorithm and Program) - GeeksforGeeks


Image Compression : Image is stored or transmitted with having pixel value. It can be
compressed by reducing the value its every pixel contains. Image compression is basically
of two types :
1. Lossless compression : In this type of compression, after recovering image is exactly
become same as that was before applying compression techniques and so, its quality didn’t
gets reduced.
2. Lossy compression : In this type of compression, after recovering we can’t get exactly as
older data and that’s why the quality of image gets significantly reduced. But this type of
compression results in very high compression of image data and is very useful in transmitting
image over network.
Discrete Cosine Transform is used in lossy image compression because it has very strong
energy compaction, i.e., its large amount of information is stored in very low frequency
component of a signal and rest other frequency having very small data which can be stored
by using very less number of bits (usually, at most 2 or 3 bit).
To perform DCT Transformation on an image, first we have to fetch image file information
(pixel value in term of integer having range 0 – 255) which we divides in block of 8 X 8
matrix and then we apply discrete cosine transform on that block of data.
After applying discrete cosine transform, we will see that its more than 90% data will be in
lower frequency component. For simplicity, we took a matrix of size 8 X 8 having all value
as 255 (considering image to be completely white) and we are going to perform 2-D discrete
cosine transform on that to observe the output.
Algorithm : Let we are having a 2-D variable named matrix of dimension 8 X 8 which
contains image information and a 2-D variable named dct of same dimension which contain
the information after applying discrete cosine transform. So, we have the formula
dct[i][j] = ci * cj (sum(k=0 to m-1) sum(l=0 to n-1) matrix[k][l] * cos((2*k+1) *i*pi/2*m)
* cos((2*l+1) *j*pi/2*n)

479
Chapter 65. Discrete Cosine Transform (Algorithm and Program)

where ci= 1/sqrt(m) if i=0 else ci= sqrt(2)/sqrt(m) and


similarly, cj= 1/sqrt(n) if j=0 else cj= sqrt(2)/sqrt(n)
and we have to apply this formula to all the value, i.e., from i=0 to m-1 and j=0 to n-1
Here, sum(k=0 to m-1) denotes summation of values from k=0 to k=m-1.
In this code, both m and n is equal to 8 and pi is defined as 3.142857.
C++

// CPP program to perform discrete cosine transform


#include <bits/stdc++.h>
using namespace std;
#define pi 3.142857
const int m = 8, n = 8;
  
// Function to find discrete cosine transform and print it
int dctTransform(int matrix[][n])
{
    int i, j, k, l;
  
    // dct will store the discrete cosine transform
    float dct[m][n];
  
    float ci, cj, dct1, sum;
  
    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 / sqrt(m);
            else
                ci = sqrt(2) / sqrt(m);
            if (j == 0)
                cj = 1 / sqrt(n);
            else
                cj = sqrt(2) / 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] * 
                           cos((2 * k + 1) * i * pi / (2 * m)) * 
                           cos((2 * l + 1) * j * pi / (2 * n));
                    sum = sum + dct1;
                }

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

// Java program to perform discrete cosine transform


  
import java.util.*;
  
class GFG 
{
    public static int n = 8,m = 8;
    public static double pi = 3.142857;
      
    // Function to find discrete cosine transform and print it
    static strictfp void dctTransform(int matrix[][])
    {
        int i, j, k, l;
   
        // dct will store the discrete cosine transform
        double[][] dct = new double[m][n];
   
        double ci, cj, dct1, sum;

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)

                         { 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);
    }
}
  
// Contributed by Pramod Kumar

Output:

2039.999878 -1.168211 1.190998 -1.230618 1.289227 -1.370580 1.480267 -1.6269


-1.167731 0.000664 -0.000694 0.000698 -0.000748 0.000774 -0.000837 0.0009
1.191004 -0.000694 0.000710 -0.000710 0.000751 -0.000801 0.000864 -0.0009
-1.230645 0.000687 -0.000721 0.000744 -0.000771 0.000837 -0.000891 0.0009
1.289146 -0.000751 0.000740 -0.000767 0.000824 -0.000864 0.000946 -0.0010
-1.370624 0.000744 -0.000820 0.000834 -0.000858 0.000898 -0.000998 0.0010
1.480278 -0.000856 0.000870 -0.000895 0.000944 -0.001000 0.001080 -0.0011
-1.626932 0.000933 -0.000940 0.000975 -0.001024 0.001089 -0.001175 0.0012

Source

https://www.geeksforgeeks.org/discrete-cosine-transform-algorithm-program/

483
Chapter 66

Distance of nearest cell having 1


in a binary matrix

Distance of nearest cell having 1 in a binary matrix - GeeksforGeeks


Given a binary matrix of N x M, containing at least a value 1. The task is to find the
distance of nearest 1 in the matrix for each cell. The distance is calculated as |i1 – i2 | +
|j1 – j2 |, where i1 , j1 are the row number and column number of the current cell and i2 , j2
are the row number and column number of the nearest cell having value 1.
Examples:

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

For cell at (0, 0), nearest 1 is at (0, 3),


so distance = (0 - 0) + (3 - 0) = 3.
Similarly all the distance can be calculated.

Method 1 (Brute Force):


The idea is to traverse the matrix for each cell and find the minimum distance.
Below is the implementation of this approach:

C++

484
Chapter 66. Distance of nearest cell having 1 in a binary matrix

// C++ program to find distance of nearest


// cell having 1 in a binary matrix.
#include<bits/stdc++.h>
#define N 3
#define M 4
using namespace std;
  
// Print the distance of nearest cell
// having 1 for each cell.
void printDistance(int mat[N][M])
{
    int ans[N][M];
  
    // Initalize the answer matrix with INT_MAX.
    for (int i = 0; i < N; i++)
        for (int j = 0; j < M; j++)
            ans[i][j] = INT_MAX;
  
    // For each cell
    for (int i = 0; i < N; i++)
        for (int j = 0; j < M; j++)
        {
            // Traversing the whole matrix
            // to find the minimum distance.
            for (int k = 0; k < N; k++)
                for (int 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 (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
            cout << ans[i][j] << " ";
  
        cout << endl;
    }
}
  
// Driven Program
int main()
{

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

// Java program to find distance of nearest


// cell having 1 in a binary matrix.
  
import java.io.*;
  
class GFG {
      
    static int N = 3;
    static int M = 4;
      
    // Print the distance of nearest cell
    // having 1 for each cell.
    static void printDistance(int mat[][])
    {
        int ans[][] = new int[N][M];
      
        // Initalize the answer matrix with INT_MAX.
        for (int i = 0; i < N; i++)
            for (int j = 0; j < M; j++)
                ans[i][j] = Integer.MAX_VALUE;
      
        // For each cell
        for (int i = 0; i < N; i++)
            for (int j = 0; j < M; j++)
            {
                // Traversing the whole matrix
                // to find the minimum distance.
                for (int k = 0; k < N; k++)
                    for (int l = 0; l < M; l++)
                    {
                        // If cell contain 1, check
                        // for minimum distance.
                        if (mat[k][l] == 1)
                            ans[i][j] =

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#

// C# program to find distance of nearest


// cell having 1 in a binary matrix.
  
using System;
  
class GFG {
      
    static int N = 3;
    static int M = 4;
      
    // Print the distance of nearest cell
    // having 1 for each cell.
    static void printDistance(int [,]mat)
    {
        int [,]ans = new int[N,M];
      
        // Initalise the answer matrix with int.MaxValue.

487
Chapter 66. Distance of nearest cell having 1 in a binary matrix

        for (int i = 0; i < N; i++)


            for (int j = 0; j < M; j++)
                ans[i,j] = int.MaxValue;
      
        // For each cell
        for (int i = 0; i < N; i++)
            for (int j = 0; j < M; j++)
            {
                // Traversing thewhole matrix
                // to find the minimum distance.
                for (int k = 0; k < N; k++)
                    for (int l = 0; l < M; l++)
                    {
                        // If cell contain 1, check
                        // for minimum distance.
                        if (mat[k,l] == 1)
                            ans[i,j] =
                            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++)
                Console.Write( ans[i,j] + " ");
      
            Console.WriteLine();
        }
    }
      
    // Driven Program
    public static void Main ()
    {
        int [,]mat = { {0, 0, 0, 1},
                        {0, 0, 1, 1},
                        {0, 1, 1, 0} };
      
        printDistance(mat);
    }
}
  
// This code is contributed by anuj_67.

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

    // Driver Code


    $mat = array(array(0, 0, 0, 1),
                 array(0, 0, 1, 1),
                 array(0, 1, 1, 0));
  
    printDistance($mat);
  
// This code is contributed by anuj_67.
?>

Output:

3 2 1 0
2 1 0 0
1 0 0 1

Time Complexity: O(N2 *M2 ).

Method 2 (using BFS):


The idea is to use multisource Breadth First Search. Consider each cell as a node and each
boundary between any two adjacent cells be an edge. Number each cell from 1 to N*M. Now,
push all the node whose corresponding cell value is 1 in the matrix in the queue. Apply
BFS using this queue to find the minimum distance of the adjacent node.

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.

Below is C++ implementation of this approach:

// C++ program to find distance of nearest


// cell having 1 in a binary matrix.
#include<bits/stdc++.h>
#define MAX 500
#define N 3
#define M 4
using namespace std;
  
// Making a class of graph with bfs function.
class graph

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

Time Complexity: O(N * M).


Improved By : vt_m

Source

https://www.geeksforgeeks.org/distance-nearest-cell-1-binary-matrix/

494
Chapter 67

Divide and Conquer | Set 5


(Strassen’s Matrix
Multiplication)

Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication) - GeeksforGeeks


Given two square matrices A and B of size n x n each, find their multiplication matrix.
Naive Method
Following is a simple way to multiply two matrices.

void multiply(int A[][N], int B[][N], int C[][N])


{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            C[i][j] = 0;
            for (int k = 0; k < N; k++)
            {
                C[i][j] += A[i][k]*B[k][j];
            }
        }
    }
}

Time Complexity of above method is O(N3 ).


Divide and Conquer
Following is simple Divide and Conquer method to multiply two square matrices.
1) Divide matrices A and B in 4 sub-matrices of size N/2 x N/2 as shown in the below

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

T(N) = 8T(N/2) + O(N2)

From Master's Theorem, time complexity of above method is O(N3)


which is unfortunately same as the above naive method.

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)

Time Complexity of Strassen’s Method


Addition and Subtraction of two matrices takes O(N2 ) time. So time complexity can be
written as

T(N) = 7T(N/2) + O(N2)

From Master's Theorem, time complexity of above method is


O(NLog7) which is approximately O(N2.8074)

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)

Easy way to remember Strassen’s Matrix Equation


References:
Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E.
Leiserson, Ronald L. Rivest
https://www.youtube.com/watch?v=LOLebQ8nKHA
https://www.youtube.com/watch?v=QXY4RskLQcI

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 : LU Decomposition - GeeksforGeeks


In numerical analysis and linear algebra, LU decomposition (where ‘LU’ stands for ‘lower
upper’, and also called LU factorization) factors a matrix as the product of a lower triangular
matrix and an upper triangular matrix. Computers usually solve square systems of linear
equations using the LU decomposition, and it is also a key step when inverting a matrix,
or computing the determinant of a matrix. The LU decomposition was introduced by
mathematician Tadeusz Banachiewicz in 1938.
Let A be a square matrix. An LU factorization refers to the factorization of A, with proper
row and/or column orderings or permutations, into two factors, a lower triangular matrix L
and an upper triangular matrix U, A=LU.

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++

// CPP Program to decompose a matrix into


// lower and upper traingular matrix
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
void luDecomposition(int mat[][MAX], int n)
{
    int lower[n][n], upper[n][n];
    memset(lower, 0, sizeof(lower));

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

            cout << setw(6) << upper[i][j] << "\t";


        cout << endl;
    }
}
  
// Driver code
int main()
{
    int mat[][MAX] = { { 2, -1, -2 },
                       { -4, 6, 3 },
                       { -4, -2, 8 } };
  
    luDecomposition(mat, 3);
    return 0;
}

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:

Lower Triangular Upper Triangular


1 0 0 2 -1 -2
-2 1 0 0 4 -1
-2 -1 1 0 0 3

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/doolittle-algorithm-lu-decomposition/

504
Chapter 69

Easy way to remember


Strassen’s Matrix Equation

Easy way to remember Strassen’s Matrix Equation - GeeksforGeeks


Strassen’s matrix is a Divide and Conquer method that helps us to multiply two matrices(of
size n X n).
You can refer to the link, for having the knowledge about Strassen’s Matrix first :
Divide and Conquer | Set 5 (Strassen’s Matrix Multiplication)
But this method needs to cram few equations, so I’ll tell you the simplest way to remember
those :

505
Chapter 69. Easy way to remember Strassen’s Matrix Equation

You just need to remember 4 Rules :

• AHED (Learn it as ‘Ahead’)


• Diagonal
• Last CR
• First CR

Also, consider X as (Row +) and Y as (Column -) matrix


Follow the Steps :

• 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

Efficiently compute sums of


diagonals of a matrix

Efficiently compute sums of diagonals of a matrix - GeeksforGeeks


Given a 2D square matrix, find sum of elements in Principal and Secondary diagonals. For
example, consider the following 4 X 4 input matrix.

A00 A01 A02 A03


A10 A11 A12 A13
A20 A21 A22 A23
A30 A31 A32 A33

The primary diagonal is formed by the elements A00, A11, A22, A33.

1. Condition for Principal Diagonal: The row-column condition is row = column.


The secondary diagonal is formed by the elements A03, A12, A21, A30.
2. Condition for Secondary Diagonal: The row-column condition is row = numberOfRows
– column -1.

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++

// A simple C++ program to find sum of diagonals


#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
void printDiagonalSums(int mat[][MAX], int n)
{
    int principal = 0, secondary = 0;
    for (int i = 0; i < n; i++) {
        for (int 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];
        }
    }
  
    cout << "Principal Diagonal:" << principal << endl;
    cout << "Secondary Diagonal:" << secondary << endl;
}
  
// Driver code
int main()
{
    int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, 

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

// A simple java program to find


// sum of diagonals
import java.io.*;
  
public class GFG {
  
    static void printDiagonalSums(int [][]mat,
                                         int n)
    {
        int principal = 0, secondary = 0;
        for (int i = 0; i < n; i++) {
            for (int 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];
            }
        }
      
        System.out.println("Principal Diagonal:"
                                    + principal);
                                      
        System.out.println("Secondary Diagonal:"
                                    + secondary);
    }
  
    // Driver code
    static public void main (String[] args)
    {
          
        int [][]a = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 }, 
                      { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 } };
                      

510
Chapter 70. Efficiently compute sums of diagonals of a matrix

        printDiagonalSums(a, 4);
    }
}
  
// This code is contributed by vt_m.

C#

// A simple C# program to find sum


// of diagonals
using System;
  
public class GFG {
  
    static void printDiagonalSums(int [,]mat,
                                        int n)
    {
        int principal = 0, secondary = 0;
        for (int i = 0; i < n; i++) {
            for (int 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];
            }
        }
      
        Console.WriteLine("Principal Diagonal:"
                                  + principal);
                                    
        Console.WriteLine("Secondary Diagonal:"
                                  + secondary);
    }
  
    // Driver code
    static public void Main ()
    {
        int [,]a = { { 1, 2, 3, 4 },
                     { 5, 6, 7, 8 }, 
                     { 1, 2, 3, 4 },
                     { 5, 6, 7, 8 } };
                       

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

// This code is contrbuted by ajit


?>

Output:

Principal Diagonal:18
Secondary Diagonal:18

This code takes O(n^2) time and O(1) auxiliary space

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++

// An efficient C++ program to find sum of diagonals


#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
void printDiagonalSums(int mat[][MAX], int n)
{
    int principal = 0, secondary = 0; 
    for (int i = 0; i < n; i++) {
        principal += mat[i][i];
        secondary += mat[i][n - i - 1];        
    }
  
    cout << "Principal Diagonal:" << principal << endl;
    cout << "Secondary Diagonal:" << secondary << endl;
}
  
// Driver code
int main()
{
    int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, 
                     { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
    printDiagonalSums(a, 4);
    return 0;
}

Java

513
Chapter 70. Efficiently compute sums of diagonals of a matrix

// An efficient java program to find


// sum of diagonals
import java.io.*;
  
public class GFG {
  
    static void printDiagonalSums(int [][]mat,
                                        int n)
    {
        int principal = 0, secondary = 0; 
        for (int i = 0; i < n; i++) {
            principal += mat[i][i];
            secondary += mat[i][n - i - 1]; 
        }
      
        System.out.println("Principal Diagonal:"
                                   + principal);
                                     
        System.out.println("Secondary Diagonal:"
                                   + secondary);
    }
      
    // Driver code
    static public void main (String[] args)
    {
        int [][]a = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 }, 
                      { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 } };
      
        printDiagonalSums(a, 4);
    }
}
  
// This code is contributed by vt_m.

C#

// An efficient C#program to find


// sum of diagonals
using System;
  
public class GFG {
  
    static void printDiagonalSums(int [,]mat,
                                       int n)
    {
        int principal = 0, secondary = 0; 

514
Chapter 70. Efficiently compute sums of diagonals of a matrix

        for (int i = 0; i < n; i++) {


            principal += mat[i,i];
            secondary += mat[i,n - i - 1]; 
        }
      
        Console.WriteLine("Principal Diagonal:"
                                  + principal);
                                    
        Console.WriteLine("Secondary Diagonal:"
                                  + secondary);
    }
      
    // Driver code
    static public void Main ()
    {
        int [,]a = { { 1, 2, 3, 4 },
                     { 5, 6, 7, 8 }, 
                     { 1, 2, 3, 4 },
                     { 5, 6, 7, 8 } };
                       
        printDiagonalSums(a, 4);
    }
}
  
// This code is contributed by vt_m.

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

This code takes O(n) time and O(1) auxiliary space


Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/efficiently-compute-sums-of-diagonals-of-a-matrix/

516
Chapter 71

Final cell position in the matrix

Final cell position in the matrix - GeeksforGeeks


Given an array of list of commands U(Up), D(Down), L(Left) and R(Right) and initial cell
position (x, y) in a matrix. Find the final cell position of the object in the matrix after
following the given commands. It is assumed that the final required cell position exists in
the matrix.
Examples:

Input : command[] = "DDLRULL"


x = 3, y = 4
Output : (1, 5)

Input : command[] = "LLRUUUDRRDDDULRLLUDUUR"


x = 6, y = 5
Output : (6, 3)

Source: Flipkart Interview (SDE-1 On Campus).


Approach: Following are the steps:

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).

The final cell position is (final_x, final_y)


C++

// C++ implementation to find the final cell position


// in the given matrix

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

// Java implementation to find 


// the final cell position
// in the given matrix
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{
// function to find the 
// final cell position
// in the given matrix
static void finalPos(String 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.charAt(i) == 'U')
            cup++;
        else if (command.charAt(i) == 'D')
            cdown++;
        else if (command.charAt(i)== 'L')
            cleft++;
        else if (command.charAt(i) == 'R')
            cright++;
    }
  
    // calculate final values
    final_x = x + (cright - cleft);
    final_y = y + (cdown - cup);
  
    System.out.println("Final Position: " + 
                       "(" + final_x + ", " + 
                              final_y + ")");
}

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:

Final Position: (1, 5)

Time Complexity: O(n), where is the number of commands.


Improved By : tufan_gupta2000

Source

https://www.geeksforgeeks.org/final-cell-position-in-the-matrix/

520
Chapter 72

Find Nth term (A matrix


exponentiation example)

Find Nth term (A matrix exponentiation example) - GeeksforGeeks


We are given a recursive function that describes Nth terms in form of other terms. In this
article we have taken specific example.

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)

Step by Step method includes:


Step 1. Determine k the number of terms on which T(i) depends.
In our example T(i) depends on two terms.so, k = 2
Step 2. Determine initial values
As in this article T0=1, T1=1 are given.
Step 3. Determine TM, the transformation matrix.
This is the most important step in solving recurrence relation. In this step, we have to
make matrix of dimension k*k.
Such that
T(i)=TM*(initial value vector)
Here initial value vector is vector that contains intial value.we name this vector as initial.

Below is C++ program to implement above approach

// CPP program to find n-th term of a recursive


// function using matrix exponentiation.
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000009
  
#define ll long long int
  
  
ll power(ll n)

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

Time Complexity : O(Log n)


The same idea is used to find n-th Fibonacci number in O(Log n)

Source

https://www.geeksforgeeks.org/find-nth-term-a-matrix-exponentiation-example/

524
Chapter 73

Find Shortest distance from a


guard in a Bank

Find Shortest distance from a guard in a Bank - GeeksforGeeks


Given a matrix that is filled with ‘O’, ‘G’, and ‘W’ where ‘O’ represents open space, ‘G’
represents guards and ‘W’ represents walls in a Bank. Replace all of the O’s in the matrix
with their shortest distance from a guard, without being able to go through any walls. Also,
replace the guards with 0 and walls with -1 in output matrix.
Expected Time complexity is O(MN) for a M x N matrix.
Examples:

O ==> Open Space


G ==> Guard
W ==> Wall

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 –

// C++ program to replace all of the O's in the matrix


// with their shortest distance from a guard
#include <bits/stdc++.h>
using namespace std;
  
// store dimensions of the matrix
#define M 5
#define N 5
  
// An Data Structure for queue used in BFS
struct queueNode
{
    // i, j and distance stores x and y-coordinates
    // of a matrix cell and its distance from guard
    // respectively
    int i, j, distance;
};
  
// These arrays are used to get row and column
// numbers of 4 neighbors of a given cell
int row[] = { -1, 0, 1, 0};
int col[] = { 0, 1, 0, -1 };
  
// return true if row number and column number
// is in range
bool isValid(int i, int j)
{
    if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1))
        return false;
  
    return true;
}
  
// return true if current cell is an open area and its
// distance from guard is not calculated yet
bool isSafe(int i, int j, char matrix[][N], int output[][N])
{
    if (matrix[i][j] != 'O' || output[i][j] != -1)
        return false;
  
    return true;

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

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:

Input: mat[4][5] = { {1, 2, 3, 4, 5},


{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9},
};
Output: 5

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

// A C program to find a common element in all rows of a


// row wise sorted array
#include<stdio.h>
  
// Specify number of rows and columns
#define M 4
#define N 5
  
// Returns common element in all rows of mat[M][N]. If there is no
// common element, then -1 is returned
int findCommon(int mat[M][N])
{
    // An array to store indexes of current last column
    int column[M];
    int min_row;  // To store index of row whose current
                  // last element is minimum
  
    // Initialize current last element of all rows
    int i;
    for (i=0; i<M; i++)
        column[i] = N-1;
  
    min_row = 0; // Initialize min_row as first row
  
    // Keep finding min_row in current last column, till either
    // all elements of last column become same or we hit first column.
    while (column[min_row] >= 0)
    {
       // Find minimum in current last column
       for (i=0; i<M; i++)
       {
          if (mat[i][column[i]] < mat[min_row][column[min_row]] )
             min_row = i;
       }
  
       // eq_count is count of elements equal to minimum in current last
       // column.
       int eq_count = 0;
  
       // Travers current last column elements again to update it
       for (i=0; i<M; i++)
       {
          //  Decrease last column index of a row whose value is more
          // than minimum.
          if (mat[i][column[i]] > mat[min_row][column[min_row]])
          {

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

// A Java program to find a common 


// element in all rows of a
// row wise sorted array
  
class GFG
{
    // Specify number of rows and columns
    static final int M = 4;
    static final int N = 5;
      
    // Returns common element in all rows 
    // of mat[M][N]. If there is no
    // common element, then -1 is 
    // returned

531
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix

    static int findCommon(int mat[][])


    {
        // An array to store indexes
        // of current last column
        int column[] = new int[M];
          
        // To store index of row whose current
        // last element is minimum
        int min_row; 
      
        // Initialize current last element of all rows
        int i;
        for (i = 0; i < M; i++)
            column[i] = N - 1;
              
        // Initialize min_row as first row
        min_row = 0; 
      
        // Keep finding min_row in current last column, till either
        // all elements of last column become same or we hit first column.
        while (column[min_row] >= 0)
        {
            // Find minimum in current last column
            for (i = 0; i < M; i++)
            {
                if (mat[i][column[i]] < mat[min_row][column[min_row]] )
                    min_row = i;
            }
          
            // eq_count is count of elements equal to minimum in current last
            // column.
            int eq_count = 0;
          
            // Travers current last column elements again to update it
            for (i = 0; i < M; i++)
            {
                // Decrease last column index of a row whose value is more
                // than minimum.
                if (mat[i][column[i]] > mat[min_row][column[min_row]])
                {
                    if (column[i] == 0)
                        return -1;
                          
                    // Reduce last column index by 1
                    column[i] -= 1; 
                }
                else
                    eq_count++;

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#

// A C# program to find a common 


// element in all rows of a
// row wise sorted array
using System;
  
class GFG {
      
    // Specify number of rows and columns
    static int M = 4;
    static int N = 5;
      
    // Returns common element in all rows 
    // of mat[M][N]. If there is no
    // common element, then -1 is 
    // returned
    static int findCommon(int [,]mat)
    {
          
        // An array to store indexes

533
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix

        // of current last column


        int []column = new int[M];
          
        // To store index of row whose
        // current last element is minimum
        int min_row; 
      
        // Initialize current last element
        // of all rows
        int i;
        for (i = 0; i < M; i++)
            column[i] = N - 1;
              
        // Initialize min_row as first row
        min_row = 0; 
      
        // Keep finding min_row in current
        // last column, till either all 
        // elements of last column become
        // same or we hit first column.
        while (column[min_row] >= 0)
        {
              
            // Find minimum in current
            // last column
            for (i = 0; i < M; i++)
            {
                if (mat[i,column[i]] < 
                mat[min_row,column[min_row]] )
                    min_row = i;
            }
          
            // eq_count is count of elements 
            // equal to minimum in current
            // last column.
            int eq_count = 0;
          
            // Travers current last column 
            // elements again to update it
            for (i = 0; i < M; i++)
            {
                  
                // Decrease last column index
                // of a row whose value is more
                // than minimum.
                if (mat[i,column[i]] >
                mat[min_row,column[min_row]])
                {

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

Explanation for working of above code


Let us understand working of above code for following example.

535
Chapter 74. Find a common element in all rows of a given row-wise sorted matrix

Initially entries in last column array are N-1, i.e., {4, 4, 4, 4}


{1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9},
The value of min_row is 0, so values of last column index for rows with value greater than
5 is reduced by one. So column[] becomes {4, 3, 3, 3}.
{1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9},
The value of min_row remains 0 and and value of last column index for rows with value
greater than 5 is reduced by one. So column[] becomes {4, 2, 2, 2}.
{1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9},
The value of min_row remains 0 and value of last column index for rows with value greater
than 5 is reduced by one. So colomun[] becomes {4, 2, 1, 2}.
{1, 2, 3, 4, 5},
{2, 4, 5, 8, 10},
{3, 5, 7, 9, 11},
{1, 3, 5, 7, 9},
Now all values in current last columns of all rows is same, so 5 is returned.
A Hashing Based Solution
We can also use hashing. This solution works even if the rows are not sorted. It can be used
to print all common elements.

Step1: Create a Hash Table with all key as distinct elements


of row1. Value for all these will be 0.

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

Find a peak element in a 2D


array

Find a peak element in a 2D array - GeeksforGeeks


An element is a peak element if it is greater than or equal to its four neighbors, left, right, top
and bottom. For example neighbors for A[i][j] are A[i-1][j], A[i+1][j], A[i][j-1] and A[i][j+1].
For corner elements, missing neighbors are considered of negative infinite value.
Examples:

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

Below are some facts about this problem:


1: A Diagonal adjacent is not considered as neighbor.
2: A peak element is not necessarily the maximal element.
3: More than one such elements can exist.
4: There is always a peak element. We can see this property by creating some matrices
using pen and paper.
Method 1: (Brute Force)
Iterate through all the elements of Matrix and check if it is greater/equal to all its neighbors.
If yes, return the element.

538
Chapter 75. Find a peak element in a 2D array

Time Complexity: O(rows * columns)


Auxiliary Space: O(1)
Method 2 : (Efficient)
This problem is mainly an extension of Find a peak element in 1D array. We apply similar
Binary Search based solution here.

1. Consider mid column and find maximum element in it.


2. Let index of mid column be ‘mid’, value of maximum element in mid column be ‘max’
and maximum element be at ‘mat[max_index][mid]’.
3. If max >= A[index][mid-1] & max >= A[index][pick+1], max is a peak, return max.
4. If max < mat[max_index][mid-1], recur for left half of matrix.
5. If max < mat[max_index][mid+1], recur for right half of matrix.

Below is the C++ implementation of above algorithm:

// Finding peak element in a 2D Array.


#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to find the maximum in column 'mid'
// 'rows' is number of rows.
int findMax(int arr[][MAX], int rows, int mid, int &max)
{
    int max_index = 0;
    for (int i = 0; i < rows; i++)
    {
        if (max < arr[i][mid])
        {
            // Saving global maximum and its index
            // to check its neighbours
            max = arr[i][mid];
            max_index = i;
        }
    }
    return max_index;
}
  
// Function to find a peak element
int findPeakRec(int arr[][MAX], int rows, int columns,
                                              int mid)
{
    // Evaluating maximum of mid column. Note max is
    // passed by reference.
    int max = 0;
    int max_index = findMax(arr, rows, mid, max);

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

Find a specific pair in Matrix

Find a specific pair in Matrix - GeeksforGeeks


Given an n x n matrix mat[n][n] of integers, find the maximum value of mat(c, d) – mat(a,
b) over all choices of indexes such that both c > a and d > b.
Example:

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++

// A Naive method to find maximum value of mat[d][e]


// - ma[a][b] such that d > a and e > b
#include <bits/stdc++.h>
using namespace std;

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

// A Naive method to find maximum value of mat1[d][e]


// - ma[a][b] such that d > a and e > b
import java.io.*;
import java.util.*;
   
class GFG 
{
    // The function returns maximum value A(d,e) - A(a,b)

543
Chapter 76. Find a specific pair in Matrix

    // over all choices of indexes such that both d > a


    // and e > b.
    static int findMaxValue(int N,int mat[][])
    {
        // stores maximum value
        int maxValue = Integer.MIN_VALUE;
       
        // Consider all possible pairs mat[a][b] and
        // mat1[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 code
    public static void main (String[] args) 
    {
        int N = 5;
  
        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));
    }
}
   
// This code is contributed
// by Prakriti Gupta

Python 3

# A Naive method to find maximum 


# value of mat[d][e] - mat[a][b]
# such that d > a and e > b
N = 5
  
# The function returns maximum 

544
Chapter 76. Find a specific pair in Matrix

# value A(d,e) - A(a,b) over 


# all choices of indexes such 
# that both d > a and e > b.
def findMaxValue(mat):
      
    # stores maximum value
    maxValue = 0
  
    # Consider all possible pairs 
    # mat[a][b] and mat[d][e]
    for a in range(N - 1):
        for b in range(N - 1):
            for d in range(a + 1, N):
                for e in range(b + 1, N):
                    if maxValue < int (mat[d][e] - 
                                       mat[a][b]):
                        maxValue = int(mat[d][e] - 
                                       mat[a][b]);
  
    return maxValue;
  
# Driver Code
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 ]];
         
print("Maximum Value is " + 
       str(findMaxValue(mat)))
        
# This code is contributed 
# by ChitraNayal

C#

// A Naive method to find maximum 


// value of mat[d][e] - mat[a][b]
// such that d > a and e > b
using System;
class GFG
{
      
    // The function returns
    // maximum value A(d,e) - A(a,b)
    // over all choices of indexes 
    // such that both d > a
    // and e > b.

545
Chapter 76. Find a specific pair in Matrix

    static int findMaxValue(int N, 


                            int [,]mat)
    {
          
        //stores maximum value
        int maxValue = int.MinValue;
      
        // 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 code
    public static void Main () 
    {
        int N = 5;
  
        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}};
        Console.Write("Maximum Value is " + 
                      findMaxValue(N,mat));
    }
}
  
// This code is contributed 
// by ChitraNayal

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

// value A(d,e) - A(a,b) over 


// all choices of indexes such 
// that both $d > $a and $e > $b.
function findMaxValue(&$mat)
{
    global $N;
      
    // stores maximum value
    $maxValue = PHP_INT_MIN;
  
    // Consider all possible 
    // pairs $mat[$a][$b] and
    // $mat[$d][$e]
    for ($a = 0; $a < $N - 1; $a++)
    for ($b = 0; $b < $N - 1; $b++)
        for ($d = $a + 1; $d < $N; $d++)
        for ($e = $b + 1; $e < $N; $e++)
            if ($maxValue < ($mat[$d][$e] - 
                             $mat[$a][$b]))
                $maxValue = $mat[$d][$e] - 
                            $mat[$a][$b];
  
    return $maxValue;
}
  
// Driver Code
$mat = array(array(1, 2, -1, -4, -20),
             array(-8, -3, 4, 2, 1),
             array(3, 8, 6, 1, 3),
             array(-4, -1, 1, 7, -6),
             array(0, -4, 10, -5, 1));
              
echo "Maximum Value is " . 
       findMaxValue($mat);
  
// This code is contributed 
// by ChitraNayal
?>

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++

// An efficient method to find maximum value of mat[d]


// - ma[a][b] such that c > a and d > b
#include <bits/stdc++.h>
using namespace std;
#define 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.
int findMaxValue(int mat[][N])
{
    //stores maximum value
    int maxValue = INT_MIN;
  
    // maxArr[i][j] stores max of elements in matrix
    // from (i, j) to (N-1, N-1)
    int maxArr[N][N];
  
    // 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
    int maxv = mat[N-1][N-1];  // Initialize max
    for (int j = N - 2; j >= 0; j--)
    {
        if (mat[N-1][j] > maxv)
            maxv = mat[N - 1][j];
        maxArr[N-1][j] = maxv;
    }
  
    // preprocess last column
    maxv = mat[N - 1][N - 1];  // Initialize max
    for (int i = N - 2; i >= 0; i--)
    {
        if (mat[i][N - 1] > maxv)
            maxv = mat[i][N - 1];
        maxArr[i][N - 1] = maxv;
    }
  
    // preprocess rest of the matrix from bottom
    for (int i = N-2; i >= 0; i--)
    {
        for (int j = N-2; j >= 0; j--)
        {
            // Update maxValue

548
Chapter 76. Find a specific pair in Matrix

            if (maxArr[i+1][j+1] - mat[i][j] >


                                            maxValue)
                maxValue = maxArr[i + 1][j + 1] - mat[i][j];
  
            // set maxArr (i, j)
            maxArr[i][j] = max(mat[i][j],
                               max(maxArr[i][j + 1],
                                   maxArr[i + 1][j]) );
        }
    }
  
    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

// An efficient method to find maximum value of mat1[d]


// - ma[a][b] such that c > a and d > b
import java.io.*;
import java.util.*;
   
class GFG 
{
    // The function returns maximum value A(c,d) - A(a,b)
    // over all choices of indexes such that both c > a
    // and d > b.
    static int findMaxValue(int N,int mat[][])
    {
        //stores maximum value
        int maxValue = Integer.MIN_VALUE;
       
        // maxArr[i][j] stores max of elements in matrix

549
Chapter 76. Find a specific pair in Matrix

        // from (i, j) to (N-1, N-1)


        int maxArr[][] = new int[N][N];
       
        // 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
        int maxv = mat[N-1][N-1];  // Initialize max
        for (int j = N - 2; j >= 0; j--)
        {
            if (mat[N-1][j] > maxv)
                maxv = mat[N - 1][j];
            maxArr[N-1][j] = maxv;
        }
       
        // preprocess last column
        maxv = mat[N - 1][N - 1];  // Initialize max
        for (int i = N - 2; i >= 0; i--)
        {
            if (mat[i][N - 1] > maxv)
                maxv = mat[i][N - 1];
            maxArr[i][N - 1] = maxv;
        }
       
        // preprocess rest of the matrix from bottom
        for (int i = N-2; i >= 0; i--)
        {
            for (int j = N-2; j >= 0; j--)
            {
                // Update maxValue
                if (maxArr[i+1][j+1] - mat[i][j] > maxValue)
                    maxValue = maxArr[i + 1][j + 1] - mat[i][j];
       
                // set maxArr (i, j)
                maxArr[i][j] = Math.max(mat[i][j],
                                   Math.max(maxArr[i][j + 1],
                                       maxArr[i + 1][j]) );
            }
        }
       
        return maxValue;
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        int N = 5;

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#

// An efficient method to find 


// maximum value of mat1[d]
// - ma[a][b] such that c > a 
// and d > b
using System;
class GFG  {
      
    // The function returns
    // maximum value A(c,d) - A(a,b)
    // over all choices of indexes 
    // such that both c > a
    // and d > b.
    static int findMaxValue(int N, int [,]mat)
    {
          
        //stores maximum value
        int maxValue = int.MinValue;
      
        // maxArr[i][j] stores max 
        // of elements in matrix
        // from (i, j) to (N-1, N-1)
        int [,]maxArr = new int[N, N];
      
        // 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
         // Initialize max

551
Chapter 76. Find a specific pair in Matrix

        int maxv = mat[N - 1, N - 1];


        for (int j = N - 2; j >= 0; j--)
        {
            if (mat[N - 1, j] > maxv)
                maxv = mat[N - 1, j];
            maxArr[N - 1, j] = maxv;
        }
      
        // preprocess last column
        // Initialize max
        maxv = mat[N - 1,N - 1]; 
        for (int i = N - 2; i >= 0; i--)
        {
            if (mat[i, N - 1] > maxv)
                maxv = mat[i,N - 1];
            maxArr[i,N - 1] = maxv;
        }
      
        // preprocess rest of the
        // matrix from bottom
        for (int i = N - 2; i >= 0; i--)
        {
            for (int j = N - 2; j >= 0; j--)
            {
                  
                // Update maxValue
                if (maxArr[i + 1,j + 1] - 
                     mat[i, j] > maxValue)
                    maxValue = maxArr[i + 1,j + 1] - 
                                         mat[i, j];
      
                // set maxArr (i, j)
                maxArr[i,j] = Math.Max(mat[i, j],
                              Math.Max(maxArr[i, j + 1],
                              maxArr[i + 1, j]) );
            }
        }
      
        return maxValue;
    }
      
    // Driver code
    public static void Main () 
    {
        int N = 5;
  
        int [,]mat = {{ 1, 2, -1, -4, -20 },
                      { -8, -3, 4, 2, 1 },

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

    // preprocess last column


    $maxv = $mat[$N - 1][$N - 1]; // Initialize max
    for ($i = $N - 2; $i >= 0; $i--)
    {
        if ($mat[$i][$N - 1] > $maxv)
            $maxv = $mat[$i][$N - 1];
        $maxArr[$i][$N - 1] = $maxv;
    }
  
    // preprocess rest of the
    // matrix from bottom
    for ($i = $N - 2; $i >= 0; $i--)
    {
        for ($j = $N - 2; $j >= 0; $j--)
        {
            // Update maxValue
            if ($maxArr[$i + 1][$j + 1] - 
                $mat[$i][$j] > $maxValue)
                $maxValue = $maxArr[$i + 1][$j + 1] - 
                            $mat[$i][$j];
  
            // set maxArr (i, j)
            $maxArr[$i][$j] = max($mat[$i][$j],
                              max($maxArr[$i][$j + 1],
                                  $maxArr[$i + 1][$j]));
        }
    }
  
    return $maxValue;
}
  
// Driver Code
$mat = array(array(1, 2, -1, -4, -20),
             array(-8, -3, 4, 2, 1),
             array(3, 8, 6, 1, 3),
             array(-4, -1, 1, 7, -6),
             array(0, -4, 10, -5, 1)
                    );
echo "Maximum Value is ". 
      findMaxValue($mat);
  
// This code is contributed 
// by ChitraNayal
?>

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

Find all permuted rows of a


given row in a matrix

Find all permuted rows of a given row in a matrix - GeeksforGeeks


We are given a m*n matrix of positive integers and a row number. The task is to find all
rows in given matrix which are permutations of given row elements. It is also given that
values in every row are distinct.
Examples:

Input : mat[][] = {{3, 1, 4, 2},


{1, 6, 9, 3},
{1, 2, 3, 4},
{4, 3, 2, 1}}
row = 3
Output: 0, 2
Rows at indexes 0 and 2 are permutations of
row at index 3.

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

// C++ program to find all permutations of a given row


#include<bits/stdc++.h>

556
Chapter 77. Find all permuted rows of a given row in a matrix

#define MAX 100


  
using namespace std;
  
// Function to find all permuted rows of a given row r
void permutatedRows(int mat[][MAX], int m, int n, int r)
{
    // Creating an empty set
    unordered_set<int> s;
  
    // Count frequencies of elements in given row r
    for (int j=0; j<n; j++)
        s.insert(mat[r][j]);
  
    // Traverse through all remaining rows
    for (int i=0; i<m; i++)
    {
        // we do not need to check for given row r
        if (i==r)
            continue;
  
        // initialize hash i.e; count frequencies
        // of elements in row i
        int j;
        for (j=0; j<n; j++)
            if (s.find(mat[i][j]) == s.end())
                break;
        if (j != n)
           continue;
  
        cout << i << ", ";
    }
}
  
// Driver program to run the case
int main()
{
    int m = 4, n = 4,r = 3;
    int mat[][MAX] = {{3, 1, 4, 2},
                      {1, 6, 9, 3},
                      {1, 2, 3, 4},
                      {4, 3, 2, 1}};
    permutatedRows(mat, m, n, r);
    return 0;
}

Python3

557
Chapter 77. Find all permuted rows of a given row in a matrix

# Python program to find all


# permutations of a given row
  
# Function to find all
# permuted rows of a given row r
def permutatedRows(mat, m, n, r):
  
  
    # Creating an empty set
    s=set()
  
    # Count frequencies of
    # elements in given row r
    for j in range(n):
        s.add(mat[r][j])    
  
    # Traverse through all remaining rows
    for i in range(m):
  
        # we do not need to check
        # for given row r
        if i == r:
            continue
  
        # initialize hash i.e
        # count frequencies
        # of elements in row i
        for j in range(n):
            if mat[i][j] not in s:
  
                # to avoid the case when last
                # element does not match
                j = j - 2
                break;
        if j + 1 != n:
            continue
        print(i)
              
      
  
# Driver program to run the case
m = 4
n = 4
r = 3
mat = [[3, 1, 4, 2],
       [1, 6, 9, 3],
       [1, 2, 3, 4],
       [4, 3, 2, 1]]

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

Time complexity : O(m*n)


Auxiliary space : O(n)
Another approach to the solution using Standard Template Library(STL):

CPP

// C++ program to find all permutations of a given row


#include<bits/stdc++.h>
#define MAX 100
  
using namespace std;
  
// Function to find all permuted rows of a given row r
void permutatedRows(int mat[][MAX], int m, int n, int r)
{
   for (int i=0; i<m&&i!=r; i++){
        if(is_permutation(mat[i],mat[i]+n,mat[r])) cout<<i<<",";
    }
}
  
// Driver program to run the case
int main()
{
    int m = 4, n = 4,r = 3;
    int mat[][MAX] = {{3, 1, 4, 2},
                      {1, 6, 9, 3},
                      {1, 2, 3, 4},
                      {4, 3, 2, 1}};
    permutatedRows(mat, m, n, r);
    return 0;
}

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

Find all rectangles filled with 0

Find all rectangles filled with 0 - GeeksforGeeks


We have one 2D array, filled with zeros and ones. We have to find the starting point and
ending point of all rectangles filled with 0. It is given that rectangles are separated and do
not touch each other however they can touch the boundary of the array.A rectangle might
contain only one element.
Examples:

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]
]

Step 1: Look for the 0 row-wise and column-wise


Step 2: When you encounter any 0, save its position in output array and using loop change
all related 0 with this position in any common number so that we can exclude it from
processing next time.
Step 3: When you change all related 0 in Step 2, store last processed 0’s location in output
array in the same index.
Step 4: Take Special care when you touch the edge, by not subtracting -1 because the loop
has broken on the exact location.
Below is the implementation of above approach:

# Python program to find all 


# rectangles filled with 0
  
def findend(i,j,a,output,index):
    x = len(a)
    y = len(a[0])
  
    # flag to check column edge case,
    # initializing with 0
    flagc = 0
  
    # flag to check row edge case,
    # initializing with 0
    flagr = 0
  
    for m in range(i,x): 
  
        # loop breaks where first 1 encounters

562
Chapter 78. Find all rectangles filled with 0

        if a[m][j] == 1: 


            flagr = 1 # set the flag
            break
  
        # pass because already processed
        if a[m][j] == 5: 
            pass
  
        for n in range(j, y): 
  
            # loop breaks where first 1 encounters
            if a[m][n] == 1:
                flagc = 1 # set the flag
                break
  
            # fill rectangle elements with any
            # number so that we can exclude
            # next time
            a[m][n] = 5
  
    if flagr == 1:
        output[index].append( m-1)
    else:
        # when end point touch the boundary
        output[index].append(m) 
  
    if flagc == 1:
        output[index].append(n-1)
    else:
        # when end point touch the boundary
        output[index].append(n) 
  
  
def get_rectangle_coordinates(a):
  
    # retrieving the column size of array
    size_of_array = len(a) 
  
    # output array where we are going
    # to store our output 
    output = [] 
  
    # It will be used for storing start
    # and end location in the same index
    index = -1
  
    for i in range(0,size_of_array):
        for j in range(0, len(a[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:

[[2, 3, 3, 5], [3, 1, 5, 1], [5, 3, 6, 5]]

Asked in Intuit

Source

https://www.geeksforgeeks.org/find-rectangles-filled-0/

564
Chapter 79

Find difference between sums of


two diagonals

Find difference between sums of two diagonals - GeeksforGeeks


Given a matrix of n X n. The task is to calculate the absolute difference between the sums
of its diagonal.
Examples:

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

// C++ program to find the difference


// between the sum of diagonal.
#include <bits/stdc++.h>
#define MAX 100
using namespace std;
  
int difference(int arr[][MAX], int n)
{
    // Initialize sums of diagonals
    int d1 = 0, d2 = 0;
  
    for (int i = 0; i < n; i++)
    {
        for (int 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);
}
  
// Driven Program
int main()
{
    int n = 3;
  
    int arr[][MAX] =
    {
        {11, 2, 4},
        {4 , 5, 6},
        {10, 8, -12}
    };
  
    cout << difference(arr, n);
    return 0;
}

Java

566
Chapter 79. Find difference between sums of two diagonals

// JAVA Code for Find difference between sums


// of two diagonals
class GFG {
      
    public static int difference(int arr[][], int n)
    {
        // Initialize sums of diagonals
        int d1 = 0, d2 = 0;
       
        for (int i = 0; i < n; i++)
        {
            for (int 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 Math.abs(d1 - d2);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int n = 3;
           
        int arr[][] =
        {
            {11, 2, 4},
            {4 , 5, 6},
            {10, 8, -12}
        };
       
        System.out.print(difference(arr, n));
         
    }
  }
// This code is contributed by Arnav Kr. Mandal.

C#

567
Chapter 79. Find difference between sums of two diagonals

// C# Code for find difference between


// sums of two diagonals
using System;
  
public class GFG
{
  
    // Function to calculate difference
    public static int difference(int[,] arr,
                                 int n)
    {
          
        // Initialize sums of diagonals
        int d1 = 0, d2 = 0;
      
        for (int i = 0; i < n; i++)
        {
            for (int 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 Math.Abs(d1 - d2);
    }
      
    // Driver Code
    public static void Main() 
    {
        int n = 3;
          
        int[,] arr ={{11, 2, 4},
                     {4 , 5, 6},
                     {10, 8, -12}};
      
        Console.Write(difference(arr, n));
          
    }
}

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

Time complexity : O(n*n)


We can optimize above solution to work in O(n) using the patterns present in indexes
of cells.

C++

// C++ program to find the difference


// between the sum of diagonal.
#include <bits/stdc++.h>
#define MAX 100
using namespace std;
  
int difference(int arr[][MAX], int n)
{
    // Initialize sums of diagonals
    int d1 = 0, d2 = 0;
  
    for (int 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);
}
  
// Driven Program
int main()
{
    int n = 3;
  
    int arr[][MAX] =
    {
        {11, 2, 4},
        {4 , 5, 6},
        {10, 8, -12}

570
Chapter 79. Find difference between sums of two diagonals

    };
  
    cout << difference(arr, n);
    return 0;
}

Java

// JAVA Code for Find difference between sums


// of two diagonals
  
class GFG {
      
    public static int difference(int arr[][], int n)
    {
        // Initialize sums of diagonals
        int d1 = 0, d2 = 0;
       
        for (int i = 0; i < n; i++)
        {
            d1 += arr[i][i];
            d2 += arr[i][n-i-1];
        }
       
        // Absolute difference of the sums
        // across the diagonals
        return Math.abs(d1 - d2);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int n = 3;
           
        int arr[][] =
        {
            {11, 2, 4},
            {4 , 5, 6},
            {10, 8, -12}
        };
       
        System.out.print(difference(arr, n));
         
    }
  }
// This code is contributed by Arnav Kr. Mandal.

C#

571
Chapter 79. Find difference between sums of two diagonals

// C# Code for find difference between 


// sums of two diagonals
using System;
  
public class GFG
  
{
      
    //Function to find difference
    public static int difference(int[,] arr,
                                 int n)
    {
          
        // Initialize sums of diagonals
        int d1 = 0, d2 = 0;
      
        for (int i = 0; i < n; i++)
        {
            d1 += arr[i, i];
            d2 += arr[i, n - i - 1];
        }
      
        // Absolute difference of the sums
        // across the diagonals
        return Math.Abs(d1 - d2);
    }
      
    // Driver Code
    public static void Main() 
    {
        int n = 3;
          
        int[,] arr ={{11, 2, 4},
                     {4 , 5, 6},
                     {10, 8, -12}};
      
        Console.Write(difference(arr, n));
          
    }
}
  
// This code is contributed by shiv_bhakt.

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

Time complexity : O(n)


Improved By : shiv_bhakt, nitin mittal

Source

https://www.geeksforgeeks.org/find-difference-between-sums-of-two-diagonals/

573
Chapter 80

Find distinct elements common


to all rows of a matrix

Find distinct elements common to all rows of a matrix - GeeksforGeeks


Given a n x n matrix. The problem is to find all the distinct elements common to all rows
of the matrix. The elements can be printed in any order.
Examples:

Input : mat[][] = { {2, 1, 4, 3},


{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} }
Output : 2 3

Input : mat[][] = { {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} }
Output : 1 3 14

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++

// C++ implementation to find distinct elements


// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
  
// function to individually sort
// each row in increasing order
void sortRows(int mat[][MAX], int n)
{
    for (int i=0; i<n; i++)
        sort(mat[i], mat[i] + n);
}
  
// function to find all the common elements
void findAndPrintCommonElements(int mat[][MAX], 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[n];
    memset(curr_index, 0, sizeof(curr_index));
    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]];
  
        bool 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)

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

// JAVA Code to find distinct elements


// common to all rows of a matrix
import java.util.*;
  

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

                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)
               System.out.print(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 function */
    public static void main(String[] args) 
    {
        int mat[][] = {  {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);
    }
  }
// This code is contributed by Arnav Kr. Mandal.

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

Method 3: It uses the concept of hashing. The following steps are:

1. Map the element of 1st row in a hash table. Let it be hash.


2. Fow row = 2 to n
3. Map each element of the current row into a temporary hash table. Let it be temp.
4. Iterate through the elements of hash and check that the elements in hash are present
in temp. If not present then delete those elements from hash.
5. When all the rows are being processed in this manner, then the elements left in hash
are the required common elements.

// C++ program to find distinct elements


// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// function to individually sort
// each row in increasing order
void findAndPrintCommonElements(int mat[][MAX], int n)
{
    unordered_set<int> us;
  
    // map elements of first row
    // into 'us'
    for (int i=0; i<n; i++)
        us.insert(mat[0][i]);
  
    for (int i=1; i<n; i++)
    {
        unordered_set<int> temp;
        // mapping elements of current row
        // in 'temp'
        for (int j=0; j<n; j++)
            temp.insert(mat[i][j]);
  
        unordered_set<int>:: iterator itr;
  
        // iterate through all the elements
        // of 'us'
        for (itr=us.begin(); itr!=us.end(); itr++)
  
            // if an element of 'us' is not present
            // into 'temp', then erase that element
            // from 'us'
            if (temp.find(*itr) == temp.end())

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

Time Complexity: O(n2 )


Space Complexity: O(n)

Source

https://www.geeksforgeeks.org/find-distinct-elements-common-rows-matrix/

580
Chapter 81

Find duplicate rows in a binary


matrix

Find duplicate rows in a binary matrix - GeeksforGeeks


Given a binary matrix whose elements are only 0 and 1, we need to print the rows which
are duplicate of rows which are already present in the matrix.
Examples:

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}.

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

This problem is mainly an extension of find unique rows in a binary matrix.


A Simple Solution is to traverse all rows one by one. For every row, check if it is present
anywhere else. If yes print the row.
Time complexity : O(ROW^2 x COL)
Auxiliary Space : O(1)
Optimal solution using Trie Trie is an efficient data structure used for strong and re-
trieval of data where character set is small. The searching complexity is optimal as key
length.

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

// C++ program to find duplicate rows


// in a binary matrix.
#include<bits/stdc++.h>
  
const int MAX = 100;
  
/*struct the Trie*/
struct Trie
{
    bool leaf;
    Trie* children[2];
};
  
/*function to get Trienode*/
Trie* getNewTrieNode()
{
    Trie* node = new Trie;
    node->children[0] = node->children[1] = NULL;
    node->leaf = false;
    return node;
}
  
/* function to insert a row in Trie*/
bool insert(Trie*& head, bool* arr, int N)
{
    Trie* curr = head;
  
    for (int i = 0; i < N; i++)
    {
        /*creating a new path if it don not exist*/
        if (curr->children[arr[i]] == NULL)
            curr->children[arr[i]] = getNewTrieNode();
  
        curr = curr->children[arr[i]];
    }
  
    /*if the row already exist return false*/
    if (curr->leaf)
        return false;
  
    /* making leaf node tree and return true*/
    return (curr->leaf = true);
}
  

582
Chapter 81. Find duplicate rows in a binary matrix

void printDuplicateRows(bool mat[][MAX], int M, int N)


{
    Trie* head = getNewTrieNode();
  
    /*inserting into Trie and checking for dulpicates*/
    for (int i = 0; i < M; i++)
  
        // If already exists
        if (!insert(head, mat[i], N))
            printf("There is a duplicate row"
                  " at position: %d \n", i+1);
  
}
  
/*driver function to check*/
int main()
{
    bool mat[][MAX] =
    {
        {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},
    };
  
    printDuplicateRows(mat, 6, 6);
    return 0;
}

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

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

Find floor and ceil in an


unsorted array

Find floor and ceil in an unsorted array - GeeksforGeeks


Given an unsorted array arr[] and an element x, find floor and ceiling of x in arr[0..n-1].
Floor of x is the largest element which is smaller than or equal to x. Floor of x doesn’t
exist if x is smaller than smallest element of arr[].
Ceil of x is the smallest element which is greater than or equal to x. Ceil of x doesn’t exist
if x is greater than greates element of arr[].
Examples:

Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}


x = 7
Output : Floor = 6
Ceiling = 8

Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}


x = 6
Output : Floor = 6
Ceiling = 6

Input : arr[] = {5, 6, 8, 9, 6, 5, 5, 6}


x = 10
Output : Floor = 9
Ceiling doesn't exist.

Method 1 (Use Sorting)


1) Sort input array.

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.

Method 2 (Use Linear Search


The idea is to traverse array and keep track of two distances with respect to x.
1) Minimum distance of element greater than or equal to x.
2) Minimum distance of element smaller than or equal to x.
Finally print elements with minimum distances.

C/C++

// C++ program to find floor and ceiling in an


// unsorted array.
#include<bits/stdc++.h>
using namespace std;
  
// Function to floor and ceiling of x in arr[]
void floorAndCeil(int arr[], int n, int x)
{
    // Indexes of floor and ceiling
    int fInd, cInd;
  
    // Distances of current floor and ceiling
    int fDist = INT_MAX, cDist = INT_MAX;
  
    for (int 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];
        }

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

// Java program to find floor and ceiling in an


// unsorted array.
import java.io.*;
  
class GFG 
{
     // Function to floor and ceiling of x in arr[]
    public static void floorAndCeil(int arr[], int x)
    {
        int n = arr.length;
          
        // Indexes of floor and ceiling
        int fInd = -1, cInd = -1;
   
        // Distances of current floor and ceiling
        int fDist = Integer.MAX_VALUE, cDist = Integer.MAX_VALUE;
   
        for (int i = 0; i < n; i++)
        {
            // If current element is closer than
            // previous ceiling.
            if (arr[i] >= x && cDist > (arr[i] - x))
            {

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#

// C# program to find floor and ceiling in an


// unsorted array.
using System;
  
class GFG {
      
    // Function to floor and ceiling of x in arr[]
    public static void floorAndCeil(int []arr, int x)
    {
        int n = arr.Length;
          
        // Indexes of floor and ceiling
        int fInd = -1, cInd = -1;
  

587
Chapter 82. Find floor and ceil in an unsorted array

        // Distances of current floor and ceiling


        int fDist = int.MaxValue,
            cDist =int.MaxValue;
              
        for (int 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 == int.MaxValue)
            Console.Write("Floor doesn't exist " );
        else
            Console.WriteLine("Floor is " + arr[fInd]);
  
        if(cDist == int.MaxValue)
        Console.Write("Ceil doesn't exist ");
        else
            Console.Write("Ceil is " + arr[cInd]);
    }
      
    // Driver code
    public static void Main () 
    {
        int []arr = {5, 6, 8, 9, 6, 5, 5, 6};
        int x = 7;
          
        floorAndCeil(arr, x);
    }
}
  
// This code is contributed by nitin mittal.

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

Time Complexity : O(n)


Auxiliary Space : O(1)
Related Articles :
Ceiling in a sorted array
Floor in a sorted array
Improved By : nitin mittal, Sam007

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

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.

/* Java program to Find a 2-D array is completely


traversed or not by following the cell values */
import java.io.*;
  
class Cell {
    int x;
    int y;
  
    // Cell class constructor
    Cell(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
  
public class MoveCellPerCellValue {
  
    // function which tells all cells are visited or not
    public boolean isAllCellTraversed(Cell grid[][])
    {
        boolean[][] visited = 
              new boolean[grid.length][grid[0].length];
  
        int total = grid.length * grid[0].length;
        // starting cell values
        int startx = grid[0][0].x;
        int starty = grid[0][0].y;
  
        for (int i = 0; i < total - 2; i++) {
  
            // if we get null before the end of loop 
            // then returns false. Because it means we 
            // didn't traverse all the cells

592
Chapter 83. Find if a 2-D array is completely traversed or not by following the cell values

            if (grid[startx][starty] == null) 


                return false;
              
            // If found cycle then return false
            if (visited[startx][starty] == true) 
                return false;
              
            visited[startx][starty] = true;
            int x = grid[startx][starty].x;
            int y = grid[startx][starty].y;
  
            // Update startx and starty values to next
            // cell values
            startx = x;
            starty = y;
        }
  
        // finally if we reach our goal then returns true
        if (grid[startx][starty] == null) 
            return true;
          
        return false;
    }
  
    /* Driver program to test above function */
    public static void main(String args[])
    {
        Cell cell[][] = new Cell[3][2];
        cell[0][0] = new Cell(0, 1);
        cell[0][1] = new Cell(2, 0);
        cell[1][0] = null;
        cell[1][1] = new Cell(1, 0);
        cell[2][0] = new Cell(2, 1);
        cell[2][1] = new Cell(1, 1);
  
        MoveCellPerCellValue mcp = new MoveCellPerCellValue();
        System.out.println(mcp.isAllCellTraversed(cell));
    }
}

Output:

true

Time Complexity : O(N)


Auxiliary Space : O(M*N)

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

Find if given matrix is Toeplitz


or not

Find if given matrix is Toeplitz or not - GeeksforGeeks


Given a square matrix, find if it’s a Toeplitz matrix or not. A Toeplitz (or diagonal-constant)
matrix is a matrix in which each descending diagonal from left to right is constant, i.e.,
all elements in a diagonal are same.
In general, any n×n matrix mat[][] is a Toeplitz matrix if every cell mat[i][j] is same as
mat[i-1][j-1], mat[i+1][j+1], mat[i-2][j-2], mat[i+2][j+2], .. for every cell mat[i][j] and all the
valid cells mat[i+k][j+k] or mat[i-k][j-k]

Examples :

Input: mat[N][N] = {{ 6, 7, 8},


{ 4, 6, 7},
{ 1, 4, 6}},
Output : True;
Values in all diagonals are same.

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;

Input: mat[N][N] = {{ 6, 3, 8},


{ 4, 9, 7},
{ 1, 4, 6}},
Output : False;

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++

// C++ program to check whether given matrix


// is a Toeplitz matrix or not
#include <iostream>
using namespace std;
#define N 5
#define M 4
  
// Function to check if all elements present in
// descending diagonal starting from position
// (i, j) in the matrix are all same or not
bool checkDiagonal(int mat[N][M], int i, int j)
{
    int 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
bool isToepliz(int mat[N][M])
{
    // do for each element in first row
    for (int i = 0; i < M; i++)
    {
        // check descending diagonal starting from
        // position (0, j) in the matrix
        if (!checkDiagonal(mat, 0, i))
            return false;
    }
  
    // do for each element in first column
    for (int i = 1; i < N; i++)
    {
        // check descending diagonal starting from
        // position (i, 0) in the matrix

596
Chapter 84. Find if given matrix is Toeplitz or not

        if (!checkDiagonal(mat, i, 0))


            return false;
    }
  
    // we only reach here when each descending
    // diagonal from left to right is same
    return true;
}
  
// Driver code
int main()
{
    int mat[N][M] =
    {
        { 6, 7, 8, 9 },
        { 4, 6, 7, 8 },
        { 1, 4, 6, 7 },
        { 0, 1, 4, 6 },
        { 2, 0, 1, 4 }
    };
  
    if (isToepliz(mat))
        cout << "Matrix is a Toepliz ";
    else
        cout << "Matrix is not a Toepliz ";
  
    return 0;
}

Java

// Java program to check whether given matrix


// is a Toeplitz matrix or not
import java.io.*;
  
class GFG 
{
    public static int N = 5;
    public static int M = 4;
      
    // Function to check if all elements present in
    // descending diagonal starting from position
    // (i, j) in the matrix are all same or not
    static boolean checkDiagonal(int mat[][], int i, int j)
    {
        int res = mat[i][j];
        while (++i < N && ++j < M)
        {

597
Chapter 84. Find if given matrix is Toeplitz or not

            // 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
    static boolean isToepliz(int mat[][])
    {
        // do for each element in first row
        for (int i = 0; i < M; i++)
        {
            // check descending diagonal starting from
            // position (0, j) in the matrix
            if (!checkDiagonal(mat, 0, i))
                return false;
        }
   
        // do for each element in first column
        for (int i = 1; i < N; i++)
        {
            // check descending diagonal starting from
            // position (i, 0) in the matrix
            if (!checkDiagonal(mat, i, 0))
                return false;
        }
   
        // we only reach here when each descending
        // diagonal from left to right is same
        return true;
    }
      
    // driver program
    public static void main (String[] args) 
    {
        int mat[][] = { { 6, 7, 8, 9 },
                        { 4, 6, 7, 8 },
                        { 1, 4, 6, 7 },
                        { 0, 1, 4, 6 },
                        { 2, 0, 1, 4 }
                      };
   
        if (isToepliz(mat))

598
Chapter 84. Find if given matrix is Toeplitz or not

            System.out.println("Matrix is a Toepliz ");


        else
            System.out.println("Matrix is not a Toepliz ");
    }
}
  
// This code is contributed by Pramod Kumar

Python3

# Python3 program to check whether given 


# matrix is a Toeplitz matrix or not
N = 5
M = 4
  
# Function to check if all elements present in
# descending diagonal starting from position
# (i, j) in the matrix are all same or not
def checkDiagonal(mat, i, j):
    res = mat[i][j]
    i += 1
    j += 1
      
    while (i < N and j < M):
          
        # mismatch found
        if (mat[i][j] != res):
            return False
              
        i += 1
        j += 1
  
    # 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
def isToeplitz(mat):
      
    # do for each element in first row
    for j in range(M):
          
        # check descending diagonal starting from
        # position (0, j) in the matrix
        if not(checkDiagonal(mat, 0, j)):
            return False
      

599
Chapter 84. Find if given matrix is Toeplitz or not

    # do for each element in first column


    for i in range(1, N): 
          
        # check descending diagonal starting 
        # from position (i, 0) in the matrix
        if not(checkDiagonal(mat, i, 0)):
            return False
          
    return True
  
# Driver Code 
if __name__ == "__main__":
          
    mat = [[6, 7, 8, 9],
          [4, 6, 7, 8],
          [1, 4, 6, 7],
          [0, 1, 4, 6],
          [2, 0, 1, 4]]
  
    if(isToeplitz(mat)):
        print("Matrix is a Toeplitz")
    else:
        print("Matrix is not a Toeplitz")
  
# This code is contributed by Jasmine K Grewal

C#

// C# program to check whether given matrix


// is a Toeplitz matrix or not
using System;
  
class GFG {
  
    public static int N = 5;
    public static int M = 4;
      
    // Function to check if all elements present in
    // descending diagonal starting from position
    // (i, j) in the matrix are all same or not
    static bool checkDiagonal(int[,] mat, int i, int j)
    {
  
        int res = mat[i,j];
        while (++i < N && ++j < M)
        {
  
            // mismatch found

600
Chapter 84. Find if given matrix is Toeplitz or not

            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
    static bool isToepliz(int [,] mat)
    {
  
        // do for each element in first row
        for (int i = 0; i < M; i++)
        {
  
            // check descending diagonal starting from
            // position (0, j) in the matrix
            if (!checkDiagonal(mat, 0, i))
                return false;
        }
  
        // do for each element in first column
        for (int i = 1; i < N; i++)
        {
  
            // check descending diagonal starting from
            // position (i, 0) in the matrix
            if (!checkDiagonal(mat, i, 0))
                return false;
        }
  
        // we only reach here when each descending
        // diagonal from left to right is same
        return true;
    }
      
    // driver program
    public static void Main () 
    {
        int [,] mat = { { 6, 7, 8, 9 },
                        { 4, 6, 7, 8 },
                        { 1, 4, 6, 7 },
                        { 0, 1, 4, 6 },
                        { 2, 0, 1, 4 }
                    };

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

        // check descending diagonal 


        // starting from position 
        // (0, j) in the matrix
        if (!checkDiagonal($mat, 0, $i))
            return false;
    }
  
    // do for each element 
    // in first column
    for ($i = 1; $i < $N; $i++)
    {
        // check descending diagonal
        // starting from position 
        // (i, 0) in the matrix
        if (!checkDiagonal($mat, $i, 0))
            return false;
    }
  
    // we only reach here when 
    // each descending diagonal 
    // from left to right is same
    return true;
}
  
// Driver code
$mat = array(array( 6, 7, 8, 9 ),
             array( 4, 6, 7, 8 ),
             array( 1, 4, 6, 7 ),
             array( 0, 1, 4, 6 ),
             array( 2, 0, 1, 4 ));
  
if (isToepliz($mat))
    echo "Matrix is a Toepliz ";
else
    echo "Matrix is not a Toepliz ";
  
// This code is contributed 
// by nitin mittal. 
?>

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

Find if there is a rectangle in


binary matrix with corners as 1

Find if there is a rectangle in binary matrix with corners as 1 - GeeksforGeeks


There is a given binary matrix, we need to find if there exists any rectangle or square in the
given matrix whose all four corners are equal to 1.
Examples:

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

Brute Force Approach-


We start scanning the matrix whenever we find a 1 at any index then we try for all the
combination for index with which we can form the rectangle.
algorithm-

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

for l=j+1 to columns


if (matrix[i][k]==1 &&
matrix[l][i]==1 &&
m[l][k]==1)
return true
return false

-Time Complexity of this solutions- O(m^2*n^2)

// A brute force approach based CPP program to


// find if there is a rectangle with 1 as corners.
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if there is a rectangle with
// 1 as corners.
bool isRectangle(const vector<vector<int> >& m)
{
    // finding row and column size
    int rows = m.size();
    if (rows == 0)
        return false;
    int columns = m[0].size();
  
    // scanning the matrix
    for (int y1 = 0; y1 < rows; y1++)
      for (int x1 = 0; x1 < columns; x1++)
  
        // if any index found 1 then try
        // for all rectangles
        if (m[y1][x1] == 1)
          for (int y2 = y1 + 1; y2 < rows; y2++)
            for (int x2 = x1 + 1; x2 < columns; x2++)
               if (m[y1][x2] == 1 &&
                   m[y2][x1] == 1 &&
                     m[y2][x2] == 1)
                            return true;
    return false;
}
  
// Driver code
int main()
{
    vector<vector<int> > mat = { { 1, 0, 0, 1, 0 },
                                 { 0, 0, 1, 0, 1 },
                                 { 0, 0, 0, 1, 0 },
                                 { 1, 0, 1, 0, 1 } };
    if (isRectangle(mat))

606
Chapter 85. Find if there is a rectangle in binary matrix with corners as 1

        cout << "Yes";


    else
        cout << "No";
}

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)

// An efficient approach based CPP program to


// find if there is a rectangle with 1 as
// corners.
#include <bits/stdc++.h>
using namespace std;
  
// Returns true if there is a rectangle with
// 1 as corners.
bool isRectangle(const vector<vector<int> >& matrix)
{
    // finding row and column size
    int rows = matrix.size();
    if (rows == 0)
        return false;
  
    int columns = matrix[0].size();
  
    // map for storing the index of combination of 2 1's
    unordered_map<int, unordered_set<int> > table;
  
    // scanning from top to bottom line by line
    for (int i = 0; i < rows; ++i) {
  
     for (int j = 0; j < columns - 1; ++j) {
        for (int k = j + 1; k < columns; ++k) {
  
          // if found two 1's in a column
          if (matrix[i][j] == 1 &&
              matrix[i][k] == 1) {
  
            // check if there exists 1's in same

607
Chapter 85. Find if there is a rectangle in binary matrix with corners as 1

            // row previously then return true


            if (table.find(j) != table.end() &&
                table[j].find(k) != table[j].end())
                        return true;
  
            if (table.find(k) != table.end() &&
                table[k].find(j) != table[k].end())
                        return true;
  
            // store the indexes in hashset
            table[j].insert(k);
            table[k].insert(j);
          }
        }
      }
    }
    return false;
}
  
// Driver code
int main()
{
    vector<vector<int> > mat = { { 1, 0, 0, 1, 0 },
                                 { 0, 0, 1, 0, 1 },
                                 { 0, 0, 0, 1, 0 },
                                { 1, 0, 1, 0, 1 } };
    if (isRectangle(mat))
        cout << "Yes";
    else
        cout << "No";
}

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

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

Input: mat[][] = { {a, c, d},


{h, b, e},
{i, g, f}}
Starting Point = 'e'

Output: 5
If starting point is 'e', then longest path with consecutive
characters is "e f g h i".

Input: mat[R][C] = { {b, e, f},


{h, d, a},
{i, c, a}};
Starting Point = 'b'

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++

// C++ program to find the longest consecutive path


#include<bits/stdc++.h>
#define R 3
#define C 3
using namespace std;
  
// tool matrices to recur for adjacent cells.
int x[] = {0, 1, 1, -1, 1, 0, -1, -1};
int y[] = {1, 0, 1, 1, -1, -1, 0, -1};
  
// dp[i][j] Stores length of longest consecutive path
// starting at arr[i][j].
int dp[R][C];
  
// check whether mat[i][j] is a valid cell or not.
bool isvalid(int i, int j)
{
    if (i < 0 || j < 0 || i >= R || j >= 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#

// C# program to find the longest consecutive path


using System;
  
class GFG {
      
    // 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];
      

614
Chapter 86. Find length of the longest consecutive path from a given starting character

    // check whether mat[i][j] is a valid


    // cell or not.
    static bool isvalid(int i, int j)
    {
        if (i < 0 || j < 0 || i >= R || j >= C)
            return false;
        return true;
    }
      
    // Check whether current character is 
    // adjacent to previous character 
    // (character processed in parent call)
    // or not.
    static 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.
    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]));

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

Thanks to Gaurav Ahirwar for above solution.


Improved By : nitin mittal

Source

https://www.geeksforgeeks.org/find-length-of-the-longest-consecutive-path-in-a-character-matrix/

617
Chapter 87

Find maximum element of each


row in a matrix

Find maximum element of each row in a matrix - GeeksforGeeks


Given a matrix, the task is to find the maximum element of each row.
Examples :

Input : [1, 2, 3]
[1, 4, 9]
[76, 34, 21]

Output :
3
9
76

Input : [1, 2, 3, 21]


[12, 1, 65, 9]
[1, 56, 34, 2]
Output :
21
65
56

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.

Below is the implementation :

# Python program to find maximum 

618
Chapter 87. Find maximum element of each row in a matrix

# element of each row in a matrix


  
# importing numpy
import numpy
  
# Function to get max element
def maxelement(arr):
      
    # get number of rows and columns
    no_of_rows = len(arr)
    no_of_column = len(arr[0])
      
    for i in range(no_of_rows):
          
        # Initialize max1 to 0 at begining
        # of finding max element of each row
        max1 = 0
        for j in range(no_of_column):
            if arr[i][j] > max1 :
                max1 = arr[i][j]
                  
        # print maximum element of each row
        print(max1)
  
# Driver Code
arr = [[3, 4, 1, 8],
       [1, 4, 9, 11],
       [76, 34, 21, 1],
       [2, 1, 4, 5]]
  
# Calling the function        
maxelement(arr)

Output :

8
11
76
5

Source

https://www.geeksforgeeks.org/find-maximum-element-row-matrix/

619
Chapter 88

Find maximum length Snake


sequence

Find maximum length Snake sequence - GeeksforGeeks


Given a grid of numbers, find maximum length Snake sequence and print it. If multiple
snake sequences exists with the maximum length, print any one of them.
A snake sequence is made up of adjacent numbers in the grid such that for each number,
the number on the right or the number below it is +1 or -1 its value. For example, if you
are at location (x, y) in the grid, you can either move right i.e. (x, y+1) if that number is ±
1 or move down i.e. (x+1, y) if that number is ± 1.
For example,
9, 6, 5, 2
8, 7, 6, 5
7, 3, 1, 6
1, 1, 1, 7
In above grid, the longest snake sequence is: (9, 8, 7, 6, 5, 6, 7)
Below figure shows all possible paths –

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

// C++ program to find maximum length


// Snake sequence and print it
#include <bits/stdc++.h>
using namespace std;
#define M 4
#define N 4
  
struct Point
{
    int x, y;
};
  
// Function to find maximum length Snake sequence path
// (i, j) corresponds to tail of the snake
list<Point> findPath(int grid[M][N], int mat[M][N],
                     int i, int j)
{

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

# Python program to find maximum length


# Snake sequence and print it
  
M = 4
N = 4
  
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
  
# Function to find maximum length Snake sequence path
# (i, j) corresponds to tail of the snake
def findPath(grid, mat, i, j):
    path = list()
  
    pt = Point(i, j)
    path.append(pt)
  
    while (grid[i][j] != 0):
        if (i > 0 and grid[i][j]-1 == grid[i-1][j]):
            pt = Point(i-1, j)
            path.append(pt)
            i -= 1
        elif (j > 0 and grid[i][j]-1 == grid[i][j-1]):
            pt = Point(i, j-1)
            path.append(pt)
            j -= 1
    return path
  
# Function to find maximum length Snake sequence
def findSnakeSequence(mat):
  

624
Chapter 88. Find maximum length Snake sequence

    # table to store results of subproblems


    # initialize by 0
    lookup = [[0 for i in range(N)] for j in range(M)]
  
    # stores maximum length of Snake sequence
    max_len = 0
  
    # store cordinates to snake's tail
    max_row = 0
    max_col = 0
  
    # fill the table in bottom-up fashion
    for i in range(M):
        for j in range(N):
            # do except for (0, 0) cell
            if (i or j):
                # look above
                if (i > 0 and
                    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 and
                    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
  
    print("Maximum length of Snake sequence is:", max_len)
  
    # find maximum length Snake sequence path
    path = findPath(lookup, mat, max_row, max_col)
  
    print("Snake sequence is:")
    for ele in reversed(path):
        print(mat[ele.x][ele.y],
              " (", ele.x, ", ", ele.y, ")", sep = "")
  
# Driver code
mat = [[9, 6, 5, 2],

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 :

Maximum length of Snake sequence is: 6


Snake sequence is:
9 (0, 0)
8 (1, 0)
7 (1, 1)
6 (1, 2)
5 (1, 3)
6 (2, 3)
7 (3, 3)

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

Find median in row wise sorted


matrix

Find median in row wise sorted matrix - GeeksforGeeks


We are given a row wise sorted matrix of size r*c, we need to find the median of the matrix
given. It is assumed that r*c is always odd.
Examples:

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.

Below is implementation of above approach:


C++

// C++ program to find median of a matrix


// sorted row wise
#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// function to find median in the matrix
int binaryMedian(int m[][MAX], int r ,int c)
{
    int min = INT_MAX, max = INT_MIN;
    for (int i=0; i<r; i++)
    {
        // Finding the minimum element
        if (m[i][0] < min)
            min = m[i][0];
  
        // Finding the maximum element
        if (m[i][c-1] > max)
            max = m[i][c-1];
    }
  
    int desired = (r * c + 1) / 2;
    while (min < max)
    {
        int mid = min + (max - min) / 2;
        int place = 0;
  
        // Find count of elements smaller than mid
        for (int i = 0; i < r; ++i)
            place += upper_bound(m[i], m[i]+c, mid) - m[i];
        if (place < desired)

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

// Java program to find median of a matrix


// sorted row wise
import java.util.Arrays;
  
public class MedianInRowSorted 
{
    // function to find median in the matrix
    static int binaryMedian(int m[][],int r, int c)
    {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
          
        for(int i=0; i<r ; i++)
        {
              
            // Finding the minimum element
            if(m[i][0] < min)
                min = m[i][0];
              
            // Finding the maximum element
            if(m[i][c-1] > max)
                max = m[i][c-1];
        }
          
        int desired = (r * c + 1) / 2;
        while(min < max)
        {
            int mid = min + (max - min) / 2;
            int place = 0;
            int get = 0;

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

// This code is contributed by Sumit Ghosh

Python

# Python program to find median of matrix


# sorted row wise
  
from bisect import bisect_right as upper_bound
  
MAX = 100;
  
# Function to find median in the matrix
def binaryMedian(m, r, c):
    mi = m[0][0]
    mx = 0
    for i in range(r):
        if m[i][0] < mi:
            mi = m[i][0]
        if m[i] > mx :
            mx = m[i]
      
    desired = (r * c + 1) / 2
      
    while (mi < mx):
        mid = mi + (mx - mi) / 2
        place = [0];
          
        # Find count of elements smaller than mid
        for i in range(r):
             j = upper_bound(m[i], mid)
             place[0] = place[0] + j
        if place[0] < desired:
            mi = mid + 1
        else:
            mx = mid
    print "Median is", mi
    return    
      
# Driver code
r = 3
c = 3
m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]]
binaryMedian(m, r, c)
  
# This code is contributed by Sachin BIsht

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

Find number of endless points

Find number of endless points - GeeksforGeeks


Given a binary N x N matrix, we need to find the total number of matrix positions from
which there is an endless path. Any position (i, j) is said to have an endless path if and
only if all of the next positions in its row(i) and its column(j) should have value 1. If any
position next to (i,j) either in row(i) or in column(j) will have 0 then position (i,j) doesn’t
have any endless path.
Examples:

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

Advance Approach (Dynamic programming):


We can easily say that if there is a zero at any position, then it will block path for all the
positions left to it and top of it.

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++

// C++ program to find count of endless points

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

            if (row[i][j] && col[i][j])


                ans++;
  
    return ans;
}
  
// Driver code
int main()
{
    bool input[][MAX] = { {1, 0, 1, 1},
                         {0, 1, 1, 1},
                         {1, 1, 1, 1},
                         {0, 1, 1, 0}};
    int n = 4;
  
    cout << countEndless(input, n);
    return 0;
}

Java

// Java program to find count of endless points


class GFG {
      
    static final int MAX = 100;
      
    // Returns count of endless points
    static int countEndless(boolean input[][], int n)
    {
          
        boolean row[][] = new boolean[n][n];
        boolean col[][] = new boolean[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
            boolean isEndless = true;
            for (int i = n-1; i >= 0; i--)
            {
                  
                // encountered a '0', set the 
                // isEndless variable to false
                if (input[i][j] == false)

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#

// C# program to find count of


// endless points
using System;
  
public class GFG {
  
    // Returns count of endless points
    static int countEndless(bool [,]input, int n)
    {
          
        bool [,]row = new bool[n,n];
        bool [,]col = new bool[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 = true;
            for (int i = n - 1; i >= 0; i--)
            {
                  
                // encountered a '0', set
                // the isEndless variable
                // to false
                if (input[i,j] == false)
                    isEndless = false;
                      
                col[i,j] = isEndless;
            }
        }
      
        // Similarly, fill row matrix
        for (int i = 0; i < n; i++)
        {
            bool isEndless = true;
            for (int j = n - 1; j >= 0; j--)
            {
                if (input[i,j] == false)
                    isEndless = false;
                row[i,j] = isEndless;

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

    // every last row and fill 


    // every entry as blockage 
    // after a 0 is found.
    for ($j = 0; $j < $n; $j++)
    {
        // flag which will be zero 
        // once we get a '0' and 
        // it will be 1 otherwise
        $isEndless = 1;
        for ($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 ($i = 0; $i < $n; $i++)
    {
        $isEndless = 1;
        for ($j = $n - 1; $j >= 0; $j--)
        {
            if ($input[$i][$j] == 0)
                $isEndless = 0;
            $row[$i][$j] = $isEndless;
        }
    }
  
    // Calculate total count
    // of endless points
    $ans = 0;
    for ($i = 0; $i < $n; $i++)
        for ($j = 1; $j < $n; $j++)
  
            // If there is NO blockage 
            // or column after this point,
            // increment result.
            if ($row[$i][$j] && 
                $col[$i][$j])
                $ans++;
  
    return $ans;
}
  

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:

Improved By : Sam007, shiv_bhakt

Source

https://www.geeksforgeeks.org/find-number-endless-points/

641
Chapter 91

Find number of transformation


to make two Matrix Equal

Find number of transformation to make two Matrix Equal - GeeksforGeeks


Given two matrices A and B of order n*m. The task is to find the required number of
transformation steps so that both matrices became equal, print -1 if it is not possible.
Transformation step is as:
i) Select any one matrix out of two matrices.
ii) Choose either row/column of selected matrix.
iii) Increment every element of select row/column by 1.
Examples :

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.

The key steps behind the solution of this problem are:

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.

So make A[i][j] = A[i][j] - B[i][j].


For example,
If given matrices are,
A[2][2] : 1 1
1 1
B[2][2] : 1 2
3 4
After subtraction, A[][] becomes,
A[2][2] : 0 -1
-2 -3

-> 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.

// Update matrix A[][]


// so that only A[][]
// has to be transformed
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 transformation
for (i = 1; i < n; i++)
for (j = 1; j < m; j++)
if (A[i][j] - A[i][0] - A[0][j] + A[0][0] != 0)
return -1;

// 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

// C++ program to find


// number of countOpsation
// to make two matrix equals
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 1000;
  
int countOps(int A[][MAX], int B[][MAX], 
             int m, int n)
{
    // Update matrix A[][]
    // so that only A[][]
    // has to be countOpsed
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            A[i][j] -= B[i][j];
  
    // Check necessary condition
    // for condition for
    // existence of full countOpsation
    for (int i = 1; i < n; i++)
    for (int j = 1; j < m; j++)
        if (A[i][j] - A[i][0] - 
            A[0][j] + A[0][0] != 0)
        return -1;
  
    // If countOpsation is possible
    // calculate total countOpsation
    int result = 0;
    for (int i = 0; i < n; i++)
        result += abs(A[i][0]);
    for (int j = 0; j < m; j++)
        result += abs(A[0][j] - A[0][0]);
    return (result);
}
  
// Driver code
int main()
{
    int A[MAX][MAX] = { {1, 1, 1},
                        {1, 1, 1},
                        {1, 1, 1}};
    int B[MAX][MAX] = { {1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9}};
    cout << countOps(A, B, 3, 3) ;
    return 0;

644
Chapter 91. Find number of transformation to make two Matrix Equal

Java

// Java program to find number of


// countOpsation to make two matrix
// equals
import java.io.*;
  
class GFG 
{
      
    static int countOps(int A[][], int B[][],
                        int m, int n)
    {
          
        // Update matrix A[][] so that only
        // A[][] has to be countOpsed
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                A[i][j] -= B[i][j];
      
        // Check necessary condition for 
        // condition for existence of full
        // countOpsation
        for (int i = 1; i < n; i++)
            for (int j = 1; j < m; j++)
                if (A[i][j] - A[i][0] - 
                    A[0][j] + A[0][0] != 0)
                    return -1;
      
        // If countOpsation is possible
        // calculate total countOpsation
        int result = 0;
          
        for (int i = 0; i < n; i++)
            result += Math.abs(A[i][0]);
              
        for (int j = 0; j < m; j++)
            result += Math.abs(A[0][j] - A[0][0]);
              
        return (result);
    }
      
    // Driver code
    public static void main (String[] args)
    {
        int A[][] = { {1, 1, 1},

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#

// C# program to find number of


// countOpsation to make two matrix
// equals
using System;
  
class GFG 
{
      
    static int countOps(int [,]A, int [,]B,
                        int m, int n)
    {
          
        // Update matrix A[][] so that only
        // A[][] has to be countOpsed
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                A[i, j] -= B[i, j];
      
        // Check necessary condition for 
        // condition for existence of full
        // countOpsation
        for (int i = 1; i < n; i++)
            for (int j = 1; j < m; j++)
                if (A[i, j] - A[i, 0] - 
                    A[0, j] + A[0, 0] != 0)
                    return -1;
      
        // If countOpsation is possible
        // calculate total countOpsation
        int result = 0;
          
        for (int i = 0; i < n; i++)

646
Chapter 91. Find number of transformation to make two Matrix Equal

            result += Math.Abs(A[i, 0]);


              
        for (int j = 0; j < m; j++)
            result += Math.Abs(A[0, j] - A[0, 0]);
              
        return (result);
    }
      
    // Driver code
    public static void Main ()
    {
        int [,]A = { {1, 1, 1},
                     {1, 1, 1},
                     {1, 1, 1} };
                          
        int [,]B = { {1, 2, 3},
                     {4, 5, 6},
                     {7, 8, 9} };
                          
    Console.Write(countOps(A, B, 3, 3)) ;
  
    }
}
  
// This code is contributed by nitin mittal.

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

    for ($i = 1; $i < $n; $i++)


    for ($j = 1; $j < $m; $j++)
        if ($A[$i][$j] - $A[$i][0] - 
            $A[0][$j] + $A[0][0] != 0)
        return -1;
  
    // If countOpsation is possible
    // calculate total countOpsation
    $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 ($result);
}
  
    // Driver code
    $A = array(array(1, 1, 1),
               array(1, 1, 1),
               array(1, 1, 1));
                 
    $B = array(array(1, 2, 3),
               array(4, 5, 6),
               array(7, 8, 9));
    echo countOps($A, $B, 3, 3) ;
  
// This code is contributed by nitin mittal.
?>

Output:

12

Time Complexity : O (n*m)


Improved By : KRV, nitin mittal

Source

https://www.geeksforgeeks.org/find-number-transformation-make-two-matrix-equal/

648
Chapter 92

Find orientation of a pattern in


a matrix

Find orientation of a pattern in a matrix - GeeksforGeeks


Given a matrix of characters and a pattern, find the orientation of pattern in the matrix.
In other words, find if pattern appears in matrix in horizontal or vertical direction. Achieve
this in minimum time possible.

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

// C program for finding orientation of the pattern


// using KMP pattern searching algorithm
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 5
  
// Used in KMP Search for preprocessing the pattern
void computeLPSArray(char *pat, int M, int *lps)
{
    // length of the previous longest prefix suffix
    int len = 0;
    int i = 1;
  
    lps[0] = 0; // lps[0] is always 0
  
    // the loop calculates lps[i] for i = 1 to M-1
    while (i < M)
    {
        if (pat[i] == pat[len])
        {
            len++;
            lps[i++] = len;
        }
        else // (pat[i] != pat[len])
        {
            if (len != 0)
            {
                // This is tricky. Consider the example
                // AAACAAAA and i = 7.
                len = lps[len-1];
  
                // Also, note that we do not increment i here
            }
            else // if (len == 0)
            {
                lps[i++] = 0;
            }
        }
    }
}
  
int KMPSearch(char *pat, char *txt)
{
    int M = strlen(pat);
  
    // create lps[] that will hold the longest prefix suffix
    // values for pattern

650
Chapter 92. Find orientation of a pattern in a matrix

    int *lps = (int *)malloc(sizeof(int)*M);


    int j = 0; // index for pat[]
  
    // Preprocess the pattern (calculate lps[] array)
    computeLPSArray(pat, M, lps);
  
    int i = 0; // index for txt[]
    while (i < N)
    {
        if (pat[j] == txt[i])
        {
            j++;
            i++;
        }
        if (j == M)
        {
            // return 1 is pattern is found
            return 1;
        }
        // mismatch after j matches
        else if (i < N && pat[j] != txt[i])
        {
            // Do not match lps[0..lps[j-1]] characters,
            // they will match anyway
            if (j != 0)
                j = lps[j-1];
            else
                i = i+1;
        }
    }
    free(lps); // to avoid memory leak
    // return 0 is pattern is not found
    return 0;
}
  
// Function to find orientation of pattern in the matrix
// It uses KMP pattern searching algorithm
void findOrientation(char mat[][N], char *pat)
{
    // allocate memory for string contaning cols
    char *col = (char*) malloc(N);
  
    for (int i = 0; i < N; i++)
    {
        // search in row i
        if (KMPSearch(pat, mat[i]))
        {
            printf("Horizontal\n");

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

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:

Input: mat[][] = {{1, 1, 1, 1},


{1, 1, 0, 1},
{0, 0, 0, 0}};
Output : (1, 3)
Bit difference between row numbers 1 and 3
is maximum with value 4. Bit difference
between 1 and 2 is 1 and between 2 and 3
is 3.

Input: mat[][] = {{1 ,1 ,1 ,1 }


{1 ,0, 1 ,1 }
{0 ,1 ,0 ,0 }
{0, 0 ,0 ,0 }}
Output : (2, 3)
Bit difference between rows 2 and 3 is
maximum which is 4.

Input: mat[][] = {{1 ,0 ,1 ,1 }


{1 ,1 ,1 ,1 }
{0 ,1 ,0 ,1 }

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.

1). Create an empty Trie. Every node of Trie contains


two children for 0 and 1 bits.
2). Insert First Row of Binary matrix into Trie

3).Traverse rest of the rows of given Binary Matrix


a). For Each Row First we search maximum bit difference
with rows that we insert before that in Trie and
count bit difference
b). For every search we update maximum bit_diff count
if needed else not store pair of index that have
maximum bit difference
c). At Last Print Pair

// C++ program to Find Pair of row in Binary matrix


// that has maximum Bit difference
#include<bits/stdc++.h>
using namespace std;
  
// Maximum size of matrix
const int MAX = 100;
  
struct TrieNode
{
    int leaf; //store index of visited row
    struct TrieNode *Child[2];
};
  
// Utility function to create a new Trie node
TrieNode * getNode()
{
    TrieNode * newNode = new TrieNode;
    newNode->leaf = 0;
    newNode->Child[0] = newNode->Child[1] = NULL;
    return newNode;
}

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

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:

Input : mat[4][4] = {{1, 3, 2, 4},


{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}}
sum = 11
Output: (1, 10), (3, 8), (2, 9), (4, 7), (11, 0)

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 ).

Method 2 (Use Sorting)

• 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

// C++ program to find a pair with given sum such that


// every element of pair is in different rows.
#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to find pair for given sum in matrix
// mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
void pairSum(int mat[][MAX], int n, int sum)
{
    // First sort all the rows in ascending order
    for (int i=0; i<n; i++)
        sort(mat[i], mat[i]+n);
  
    // Select i'th row and find pair for element in i'th
    // row in j'th row whose summation is equal to given sum
    for (int i=0; i<n-1; i++)
    {
        for (int j=i+1; j<n; j++)
        {
            int left = 0, right = n-1;
            while (left<n && right>=0)
            {
                if ((mat[i][left] + mat[j][right]) == sum)
                {
                    cout << "(" << mat[i][left]
                         << ", "<< mat[j][right] << "), ";
                    left++;
                    right--;
                }
                else
                {
                    if ((mat[i][left] + mat[j][right]) < sum)
                        left++;
                    else

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

// Java program to find a pair with


// given sum such that every element
// of pair is in different rows.
import java.util.Arrays;
class GFG {
static final int MAX = 100;
  
// Function to find pair for given sum in
// matrix mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
static void pairSum(int mat[][], int n, int sum) {
      
    // First sort all the rows in ascending order
    for (int i = 0; i < n; i++)
    Arrays.sort(mat[i]);
  
    // Select i'th row and find pair for element in i'th
    // row in j'th row whose summation is equal to given sum
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int left = 0, right = n - 1;
            while (left < n && right >= 0) {
                if ((mat[i][left] + mat[j][right]) == sum) {
                System.out.print("(" + mat[i][left] + ", " +
                                     mat[j][right] + "), ");
                left++;

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:

(1, 10), (3, 8), (2, 9), (4, 7), (11, 0)

Time complexity : O(n2 logn + n^3)


Auxiliary space : O(1)

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

// C++ program to find pairs with given sum such

661
Chapter 94. Find pairs with given sum such that elements of pair are in different rows

// the two elements of pairs are from different rows


#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to find pair for given sum in matrix
// mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
void pairSum(int mat[][MAX], int n, int sum)
{
    // Create a hash and store all elements of matrix
    // as keys, and row and column numbers as values
    unordered_map<int, pair<int, int> > hm;
    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            hm[mat[i][j]] = make_pair(i, j);
  
    // Traverse the matrix again to check for every
    // element whether its pair exists or not.
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<n; j++)
        {
            // Look for remaining sum in hash
            int remSum = sum - mat[i][j];
            auto it = hm.find(remSum); // it is an iterator
                                       // of unordered_map type
  
            // If an element with value equal to remaining sum exists
            if (it != hm.end())
            {
                // Find row and column numbers of element with
                // value equal to remaining sum.
                pair<int, int> p = it->second;
                int row = p.first, col = p.second;
  
                // If row number of pair is not same as current
                // row, then print it as part of result.
                // Second condition is there to make sure that a 
                // pair is printed only once.  
                if (row != i && row > i)
                   cout << "(" << mat[i][j] << ", "
                        << mat[row][col] << "), ";
            }
        }
    }

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

Find perimeter of shapes


formed with 1s in binary matrix

Find perimeter of shapes formed with 1s in binary matrix - GeeksforGeeks


Given a matrix of N rows and M columns, consist of 0’s and 1’s. The task is to find the
perimeter of subfigure consisting only 1’s in the matrix. Perimeter of single 1 is 4 as it can
be covered from all 4 side. Perimeter of double 11 is 6.

| 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.

Below is the implementation of this approach:


C++

// C++ program to find perimeter of area coverede by


// 1 in 2D matrix consisits of 0's and  1's.
#include<bits/stdc++.h>
using namespace std;
#define R 3
#define C 5
  
// Find the number of covered side for mat[i][j].
int numofneighbour(int mat[][C], int i, int j)
{
    int count = 0;
  
    // UP
    if (i > 0 && mat[i - 1][j])
        count++;
  
    // LEFT
    if (j > 0 && mat[i][j - 1])
        count++;
  
    // DOWN
    if (i < R-1 && mat[i + 1][j])
        count++;
  
    // RIGHT
    if (j < C-1 && mat[i][j + 1])
        count++;
  
    return count;
}
  
// Returns sum of perimeter of shapes formed with 1s
int findperimeter(int mat[R][C])
{

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

// Java program to find perimeter of area


// coverede by 1 in 2D matrix consisits 
// of 0's and 1's
class GFG {
      
    static final int R = 3;
    static final int C = 5;
      
    // Find the number of covered side 
    // for mat[i][j].
    static int numofneighbour(int mat[][], 
                            int i, int j) 
    {
          
        int count = 0;
      
        // UP
        if (i > 0 && mat[i - 1][j] == 1)
            count++;

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

Time Complexity : O(RC).

Source

https://www.geeksforgeeks.org/find-perimeter-shapes-formed-1s-binary-matrix/

668
Chapter 96

Find row number of a binary


matrix having maximum
number of 1s

Find row number of a binary matrix having maximum number of 1s - GeeksforGeeks


Given a binary matrix (containing only 0 and 1) of order n*n. All rows are sorted already,
We need to find the row number with maximum number of 1s. Also find number of 1 in
that row.
Note: in case of tie, print smaller row number.
Examples :

Input : mat[3][3] = {0, 0, 1,


0, 1, 1,
0, 0, 0}
Output : Row number = 2, MaxCount = 2

Input : mat[3][3] = {1, 1, 1,


1, 1, 1,
0, 0, 0}
Output : Row number = 1, MaxCount = 3

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 :

for (int i=0, j=n-1; i<n;i++)


{
// find left most position of 1 in a row
// find 1st zero in a row
while (arr[i][j]==1)
{
row = i;
j--;
}
}
cout << "Row number =" << row+1;
cout << "MaxCount =" << n-j;

C++

// CPP program to find row with maximum 1

670
Chapter 96. Find row number of a binary matrix having maximum number of 1s

// in row sorted binary matrix


#include<bits/stdc++.h>
#define N 4
using namespace std;
  
// function for finding row with maximum 1
void findMax (int arr[][N])
{
    int row = 0, i, j;
    for (i=0, j=N-1; 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--;
        }
    }
    cout << "Row number = " << row+1;
    cout << ", MaxCount = " << N-1-j;
}
  
// driver program
int main()
{
    int arr[N][N] = {0, 0, 0, 1,
                     0, 0, 0, 1,
                     0, 0, 0, 0,
                     0, 1, 1, 1};
    findMax(arr);
    return 0;
}

Java

// Java program to find row with maximum 1


// in row sorted binary matrix
class GFG {
      
    static final int N = 4;
  
    // function for finding row with maximum 1
    static void findMax(int arr[][]) {
          
        int row = 0, i, j;
  
        for (i = 0, j = N - 1; i < N; i++) {

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

# python program to find row with


# maximum 1 in row sorted binary
# matrix
  
N = 4
  
# function for finding row with
# maximum 1
def findMax (arr):
    row = 0
    j = N - 1
    for i in range(0, N):
        # find left most position
        # of 1 in a row find 1st
        # zero in a row
        while (arr[i][j] == 1 
                     and j >= 0):
            row = i

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#

// C# program to find row with maximum


// 1 in row sorted binary matrix
using System;
  
class GFG {
      
    static int N = 4;
  
    // function for finding row with maximum 1
    static void findMax(int [,]arr)
    {
        int row = 0, i, j;
  
        for (i = 0, j = N - 1; 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--;
            }
        }
          
        Console.Write("Row number = " + (row + 1));
        Console.Write(", MaxCount = " + (N - 1 - j));
    }
      
    // Driver code
    public static void Main() 
    {

673
Chapter 96. Find row number of a binary matrix having maximum number of 1s

        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 nitin mittal

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:

Row number = 4, MaxCount = 3

Improved By : nitin mittal, vt_m, Sam007

Source

https://www.geeksforgeeks.org/find-row-number-binary-matrix-maximum-number-1s/

675
Chapter 97

Find shortest safe route in a


path with landmines

Find shortest safe route in a path with landmines - GeeksforGeeks


Given a path in the form of a rectangular matrix having few landmines arbitrarily placed
(marked as 0), calculate length of the shortest safe route possible from any cell in the first
column to any cell in the last column of the matrix. We have to avoid landmines and their
four adjacent cells (left, right, above and below) as they are also unsafe. We are allowed
to move to only adjacent cells which are not landmines. i.e. the route cannot contains any
diagonal moves.
Examples:

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 –

// C++ program to find shortest safe Route in


// the matrix with landmines
#include <bits/stdc++.h>
using namespace std;
#define R 12
#define C 10
  
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
int rowNum[] = { -1, 0, 0, 1 };
int colNum[] = { 0, -1, 1, 0 };
  
// A function to check if a given cell (x, y)
// can be visited or not
bool isSafe(int mat[R][C], int visited[R][C],
            int x, int y)
{
    if (mat[x][y] == 0 || visited[x][y])
        return false;
  
    return true;
}
  
// A function to check if a given cell (x, y) is
// a valid cell or not
bool isValid(int x, int y)
{
    if (x < R && y < C && x >= 0 && y >= 0)
        return true;
  
    return false;
}
  
// A function to mark all adjacent cells of
// landmines as unsafe. Landmines are shown with
// number 0
void markUnsafeCells(int mat[R][C])
{
    for (int i = 0; i < R; i++)
    {
        for (int j = 0; j < C; j++)

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

        min_dist = min(dist, min_dist);


        return;
    }
  
    // if current path cost exceeds minimum so far
    if (dist > min_dist)
        return;
  
    // include (i, j) in current path
    visited[i][j] = 1;
  
    // Recurse for all safe adjacent neighbours
    for (int k = 0; k < 4; k++)
    {
        if (isValid(i + rowNum[k], j + colNum[k]) &&
            isSafe(mat, visited, i + rowNum[k], j + colNum[k]))
        {
            findShortestPathUtil(mat, visited, i + rowNum[k],
                           j + colNum[k], min_dist, dist + 1);
        }
    }
  
    // Backtrack
    visited[i][j] = 0;
}
  
// A wrapper function over findshortestPathUtil()
void findShortestPath(int mat[R][C])
{
    // stores minimum cost of shortest path so far
    int min_dist = INT_MAX;
  
    // create a boolean matrix to store info about
    // cells already visited in current route
    int visited[R][C];
  
    // mark adjacent cells of landmines as unsafe
    markUnsafeCells(mat);
  
    // start from first column and take minimum
    for (int i = 0; i < R; i++)
    {
        // if path is safe from current cell
        if (mat[i][0] == 1)
        {
            // initailize visited to false
            memset(visited, 0, sizeof visited);
  

679
Chapter 97. Find shortest safe route in a path with landmines

            // find shortest route from (i, 0) to any


            // cell of last column (x, C - 1) where
            // 0 <= x < R
            findShortestPathUtil(mat, visited, i, 0,
                                 min_dist, 0);
  
            // if min distance is already found
            if(min_dist == C - 1)
                break;
        }
    }
  
    // if destination can be reached
    if (min_dist != INT_MAX)
        cout << "Length of shortest safe route is "
             << min_dist;
  
    else // if the destination is not reachable
        cout << "Destination not reachable from "
             << "given source";
}
  
// Driver code
int main()
{
    // input matrix with landmines shown with number 0
    int mat[R][C] =
    {
        { 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 }
    };
  
    // find shortest path
    findShortestPath(mat);
  
    return 0;
}

680
Chapter 97. Find shortest safe route in a path with landmines

Output:

Length of shortest safe route is 13

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

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 –

left(i, j) stores maximum number of


consecutive 1's to the left of cell (i, j)
including cell (i, j).

right(i, j) stores maximum number of


consecutive 1's to the right of cell (i, j)
including cell (i, j).

top(i, j) stores maximum number of


consecutive 1's at top of cell (i, j)
including cell (i, j).

bottom(i, j) stores maximum number of


consecutive 1's at bottom of cell (i, j)

683
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

including cell (i, j).

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;

Below is the implementation of above idea –


C++

// C++ program to find the size of the largest '+'


// formed by all 1's in given binary matrix
#include <bits/stdc++.h>
using namespace std;
  
// size of binary square matrix
#define N 10
  
// Function to find the size of the largest '+'
// formed by all 1's in given binary matrix
int findLargestPlus(int mat[N][N])
{
    // left[j][j], right[i][j], top[i][j] and
    // bottom[i][j] store maximum number of
    // consecutive 1's present to the left,

684
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

    // right, top and bottom of mat[i][j] including


    // cell(i, j) respectively
    int left[N][N], right[N][N], top[N][N],
        bottom[N][N];
  
    // initialize above four matrix
    for (int i = 0; i < N; i++)
    {
        // initialize first row of top
        top[0][i] = mat[0][i];
  
        // initialize last row of bottom
        bottom[N - 1][i] = mat[N - 1][i];
  
        // initialize first column of left
        left[i][0] = mat[i][0];
  
        // initialize last column of right
        right[i][N - 1] = mat[i][N - 1];
    }
  
    // fill all cells of above four matrix
    for (int i = 0; i < N; i++)
    {
        for (int j = 1; j < N; j++)
        {
            // calculate left matrix (filled left to right)
            if (mat[i][j] == 1)
                left[i][j] = left[i][j - 1] + 1;
            else
                left[i][j] = 0;
  
            // calculate top matrix
            if (mat[j][i] == 1)
                top[j][i] = top[j - 1][i] + 1;
            else
                top[j][i] = 0;
  
            // calculate new value of j to calculate
            // value of bottom(i, j) and right(i, j)
            j = N - 1 - j;
  
            // calculate bottom matrix
            if (mat[j][i] == 1)
                bottom[j][i] = bottom[j + 1][i] + 1;
            else
                bottom[j][i] = 0;
  

685
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

            // calculate right matrix


            if (mat[i][j] == 1)
                right[i][j] = right[i][j + 1] + 1;
            else
                right[i][j] = 0;
  
            // revert back to old j
            j = N - 1 - j;
        }
    }
  
    // n stores length of longest + found so far
    int n = 0;
  
    // compute longest +
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            // find minimum of left(i, j), right(i, j),
            // top(i, j), bottom(i, j)
            int len = min(min(top[i][j], bottom[i][j]),
                          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)
       return 4 * (n - 1) + 1;
  
    // matrix contains all 0's
    return 0;
}
  
/* Driver function to test above functions */
int main()
{
    // Binary Matrix of size N
    int mat[N][N] =
    {
        { 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 },

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

// Java program to find the size of the largest '+'


// formed by all 1's in given binary matrix
  
import java.io.*;
  
class GFG {
      
    // size of binary square matrix
    static int N = 10;
  
    // Function to find the size of the largest '+'
    // formed by all 1's in given binary matrix
    static int findLargestPlus(int mat[][])
    {
          
        // left[j][j], right[i][j], top[i][j] and
        // bottom[i][j] store maximum number of
        // consecutive 1's present to the left,
        // right, top and bottom of mat[i][j] 
        // including cell(i, j) respectively
        int left[][] = new int[N][N];
        int right[][] = new int[N][N];
        int top[][] = new int[N][N];
        int bottom[][] = new int[N][N];
  
        // initialize above four matrix
        for (int i = 0; i < N; i++) {
              
            // initialize first row of top
            top[0][i] = mat[0][i];
  
            // initialize last row of bottom

687
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

            bottom[N - 1][i] = mat[N - 1][i];


  
            // initialize first column of left
            left[i][0] = mat[i][0];
  
            // initialize last column of right
            right[i][N - 1] = mat[i][N - 1];
        }
  
        // fill all cells of above four matrix
        for (int i = 0; i < N; i++) {
            for (int j = 1; j < N; j++) {
                  
                // calculate left matrix 
                // (filled left to right)
                if (mat[i][j] == 1)
                    left[i][j] = left[i][j - 1] + 1;
                else
                    left[i][j] = 0;
  
                // calculate top matrix
                if (mat[j][i] == 1)
                    top[j][i] = top[j - 1][i] + 1;
                else
                    top[j][i] = 0;
  
                // calculate new value of j to 
                // calculate value of bottom(i, j) 
                // and right(i, j)
                j = N - 1 - j;
  
                // calculate bottom matrix
                if (mat[j][i] == 1)
                    bottom[j][i] = bottom[j + 1][i] + 1;
                else
                    bottom[j][i] = 0;
  
                // calculate right matrix
                if (mat[i][j] == 1)
                    right[i][j] = right[i][j + 1] + 1;
                else
                    right[i][j] = 0;
  
                // revert back to old j
                j = N - 1 - j;
            }
        }
  

688
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

        // n stores length of longest + found so far


        int n = 0;
  
        // compute longest +
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                // find minimum of left(i, j), 
                // right(i, j), top(i, j), 
                // bottom(i, j)
                int len = Math.min(Math.min(top[i][j], 
                    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(String[] args)
    {
          
        // 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 }
        };
        System.out.println(findLargestPlus(mat));
    }

689
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

}
  
// This code is contributed by vt_m.

C#

// C# program to find the size of the largest '+'


// formed by all 1's in given binary matrix
using System;
  
class GFG {
      
    // size of binary square matrix
    static int N = 10;
  
    // Function to find the size of the largest '+'
    // formed by all 1's in given binary matrix
    static int findLargestPlus(int [,] mat)
    {
          
        // left[j][j], right[i][j], top[i][j] and
        // bottom[i][j] store maximum number of
        // consecutive 1's present to the left,
        // right, top and bottom of mat[i][j] 
        // including cell(i, j) respectively
        int [,] left = new int[N,N];
        int [,] right = new int[N,N];
        int [,] top = new int[N,N];
        int [,] bottom = new int[N,N];
  
        // initialize above four matrix
        for (int i = 0; i < N; i++) {
              
            // initialize first row of top
            top[0,i] = mat[0,i];
  
            // initialize last row of bottom
            bottom[N - 1,i] = mat[N - 1,i];
  
            // initialize first column of left
            left[i,0] = mat[i,0];
  
            // initialize last column of right
            right[i,N - 1] = mat[i,N - 1];
        }
  
        // fill all cells of above four matrix
        for (int i = 0; i < N; i++) {

690
Chapter 98. Find size of the largest ‘+’ formed by all ones in a binary matrix

            for (int j = 1; j < N; j++) {


                  
                // calculate left matrix 
                // (filled left to right)
                if (mat[i,j] == 1)
                    left[i,j] = left[i,j - 1] + 1;
                else
                    left[i,j] = 0;
  
                // calculate top matrix
                if (mat[j,i] == 1)
                    top[j,i] = top[j - 1,i] + 1;
                else
                    top[j,i] = 0;
  
                // calculate new value of j to 
                // calculate value of bottom(i, j) 
                // and right(i, j)
                j = N - 1 - j;
  
                // calculate bottom matrix
                if (mat[j,i] == 1)
                    bottom[j,i] = bottom[j + 1,i] + 1;
                else
                    bottom[j,i] = 0;
  
                // calculate right matrix
                if (mat[i,j] == 1)
                    right[i,j] = right[i,j + 1] + 1;
                else
                    right[i,j] = 0;
  
                // revert back to old j
                j = N - 1 - j;
            }
        }
  
        // n stores length of longest + found so far
        int n = 0;
  
        // compute longest +
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
  
                // find minimum of left(i, j), 
                // right(i, j), top(i, j), 
                // bottom(i, j)
                int len = Math.Min(Math.Min(top[i,j], 

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

Time complexity of above solution is O(n2 ).


Auxiliary space used by the program is O(n2 ).
Improved By : KRV

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?

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?

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
};
  
// A simple solution to find sums for a given array of cell indexes
void printSums(int mat[][C], struct Cell arr[], int n)
{
    // Iterate through all cell indexes
    for (int i=0; i<n; i++)
    {
        int sum = 0, r = arr[i].r, c = arr[i].c;
  
        // Compute sum for current cell index
        for (int j=0; j<R; j++)
            for (int k=0; k<C; k++)
                if (j != r && k != c)
                    sum += mat[j][k];
        cout << sum << endl;
    }
}
  
// Driver program to test above
int main()
{
    int mat[][C] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}};
    struct Cell arr[] = {{0, 0}, {1, 1}, {0, 1}};
    int n = sizeof(arr)/sizeof(arr[0]);
    printSums(mat, arr, n);
    return 0;
}

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?

1. Calculate sum of matrix, call it sum.


2. Calculate sum of individual rows and columns. (row[] and col[])
3. For a cell index (i, j), the desired sum will be “sum- row[i] – col[j] + arr[i][j]”
Below is C++ implementation of above idea.

// 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

Time Complexity: O(R x C + n)


Auxiliary Space: O(R + C)
Thanks to Gaurav Ahirwar for suggesting this efficient solution.

Source

https://www.geeksforgeeks.org/find-sum-of-all-elements-in-a-matrix-except-the-elements-in-given-row-andor-colum

697
Chapter 100

Find the Surface area of a 3D


figure

Find the Surface area of a 3D figure - GeeksforGeeks

Given a N*M matrix A[][] representing a 3D figure. The height of the building at

is . Find the surface area of the figure.


Examples :

Input : N = 1, M = 1 A[][] = { {1} }


Output : 6

Explanation :
The total surface area is 6 i.e 6 side of
the figure and each are of height 1.

Input : N = 3, M = 3 A[][] = { {1, 3, 4},


{2, 2, 3},
{1, 2, 4} }
Output : 60

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++

// CPP program to find the Surface area of a 3D figure


#include <bits/stdc++.h>
using namespace std;
  
// Declaring the size of the matrix
const int M = 3;
const int N = 3;
  
// Absolute Difference between the height of
// two consecutive blocks
int contribution_height(int current, int previous)
{
    return abs(current - previous);
}
  
// Function To calculate the Total surfaceArea.
int surfaceArea(int A[N][M])
{
    int ans = 0;
  
    // Traversing the matrix.
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
  
            /* If we are traveling the topmost row in the 
            matrix, we declare the wall above it as 0
            as there is no wall above it. */
            int up = 0;
  
            /* If we are traveling the leftmost column in the 
            matrix, we declare the wall left to it as 0
            as there is no wall left it. */
            int left = 0;
  
            // If its not the topmost row
            if (i > 0)
                up = A[i - 1][j];
  
            // If its not the leftmost column
            if (j > 0)
                left = A[i][j - 1];
  
            // Summing up the contribution of by
            // the current block
            ans += contribution_height(A[i][j], up) 
                    + contribution_height(A[i][j], left);

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

// Java program to find the Surface


// area of a 3D figure
  
class GFG 
{
    // Declaring the size of the matrix
    static final int M=3;
    static final int N=3;
      
    // Absolute Difference between the height of
    // two consecutive blocks
    static int contribution_height(int current, int previous)
    {
        return Math.abs(current - previous);
    }
      

700
Chapter 100. Find the Surface area of a 3D figure

    // Function To calculate the Total surfaceArea.


    static int surfaceArea(int A[][])
    {
        int ans = 0;
      
        // Traversing the matrix.
        for (int i = 0; i < N; i++) 
        {
            for (int j = 0; j < M; j++) {
      
                /* If we are traveling the topmost 
                row in the matrix, we declare the 
                wall above it as 0 as there is no
                wall above it. */
                int up = 0;
      
                /* If we are traveling the leftmost 
                column in the matrix, we declare the
                wall left to it as 0as there is no
                wall left it. */
                int left = 0;
      
                // If its not the topmost row
                if (i > 0)
                    up = A[i - 1][j];
      
                // If its not the leftmost column
                if (j > 0)
                    left = A[i][j - 1];
      
                // Summing up the contribution of by
                // the current block
                ans += contribution_height(A[i][j], up) 
                       + contribution_height(A[i][j], left);
      
                /* 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];
            }

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#

// C# program to find the 


// Surface area of a 3D figure
using System;
  
class GFG 
{
    // Declaring the size of the matrix
    static int M=3;
    static int N=3;
      
    // Absolute Difference between the 
    // height of two consecutive blocks
    static int contribution_height(int current, int previous)
    {
        return Math.Abs(current - previous);
    }
      
    // Function To calculate the
    // Total surfaceArea.
    static int surfaceArea(int [,]A)
    {
        int ans = 0;
      
    // Traversing the matrix.
        for (int i = 0; i < N; i++) 
        {

702
Chapter 100. Find the Surface area of a 3D figure

            for (int j = 0; j < M; j++) {


      
    // If we are traveling the topmost 
    // row in the matrix, we declare the 
    // wall above it as 0 as there is no
    // wall above it.
                int up = 0;
      
    // If we are traveling the leftmost 
    // column in the matrix, we declare 
    // the wall left to it as 0as there 
    // is no wall left it. 
                int left = 0;
      
    // If its not the topmost row
                if (i > 0)
                    up = A[i - 1,j];
      
    // If its not the leftmost column
                if (j > 0)
                    left = A[i,j - 1];
      
    // Summing up the contribution  
    // of by the current block
            ans += contribution_height(A[i,j], up) 
                + contribution_height(A[i,j], left);
      
    // 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;
    }

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

            /* If we are traveling the


            topmost row in the matrix,
            we declare the wall above it 
            as 0 as there is no wall 
            above it. */
            $up = 0;
  
            /* If we are traveling the
            leftmost column in the 
            matrix, we declare the wall 
            left to it as 0 as there is
            no wall left it. */
            $left = 0;
  
            // If its not the topmost row
            if ($i > 0)
                $up = $A[$i - 1][$j];
  
            // If its not the 
            // leftmost column
            if ($j > 0)
                $left = $A[$i][$j - 1];
  
            // Summing up the 
            // contribution of by
            // the current block
            $ans += contribution_height($A[$i][$j], $up) +
                    contribution_height($A[$i][$j], $left);
              
            /* 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

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

Improved By : Mithun Kumar

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

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:

Input : mat = { { 1, 7, -6, 5 },


{ -8, 6, 7, -2 },
{ 10, -15, 3, 2 },
{ -5, 2, 0, 9 } }
k = 7

Output : (Top, Left): (0, 1)


(Bottom, Right): (2, 3)
7 -6 5
6 7 -2
-15 3 2

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.

// C++ implementation to find the largest area rectangular


// sub-matrix whose sum is equal to k
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// This function basically finds largest 'k'
// sum subarray in arr[0..n-1]. If 'k' sum
// doesn't exist, then it returns false. Else
// it returns true and sets starting and
// ending indexes as start and end.
bool sumEqualToK(int arr[], int& start,
                 int& end, int n, int k)
{
    // unordered_map 'um' implemented
    // as hash table
    unordered_map<int, int> um;
    int sum = 0, maxLen = 0;
  
    // traverse the given array
    for (int i = 0; i < n; i++) {
  
        // accumulate sum
        sum += arr[i];
  
        // when subarray starts from index '0'
        // update maxLength and start and end points
        if (sum == k) {
            maxLen = i + 1;
            start = 0;
            end = i;
        }
  
        // make an entry for 'sum' if it is
        // not present in 'um'
        if (um.find(sum) == um.end())
            um[sum] = i;

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

            // (up, left) and (down, right) which are the


            // boundary values.
            sum = sumEqualToK(temp, up, down, row, k);
            area = (down - up + 1) * (right - left + 1);
  
            // Compare no. of elements with previous
            // no. of elements in sub-Matrix.
            // If new sub-matrix has more elements
            // then update maxArea and final boundaries
            // like fup, fdown, fleft, fright
            if (sum && maxArea < area) {
                fup = up;
                fdown = down;
                fleft = left;
                fright = right;
                maxArea = area;
            }
        }
    }
  
    // If there is no change in boundaries
    // than check if mat[0][0] equals 'k'
    // If it is not equal to 'k' then print
    // that no such k-sum sub-matrix exists
    if (fup == 0 && fdown == 0 && fleft == 0 &&
        fright == 0 && mat[0][0] != k) {
        cout << "No sub-matrix with sum " << k << " exists";
        return;
    }
  
    // Print final values
  
    cout << "(Top, Left): "
         << "(" << fup << ", " << fleft
         << ")" << endl;
  
    cout << "(Bottom, Right): "
         << "(" << fdown << ", " << fright
         << ")" << endl;
  
    for (int j = fup; j <= fdown; j++) {
        for (int i = fleft; i <= fright; i++)
            cout << mat[j][i] << " ";
        cout << endl;
    }
}
  
// Driver program to test above

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:

(Top, Left): (0, 1)


(Bottom, Right): (2, 3)
7 -6 5
6 7 -2
-15 3 2

Time Complexity: O(n^3).


Auxiliary Space: O(n).

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

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:

Input: bool mat[][] = { {0, 1, 0, 1, 0},


{0, 1, 0, 1, 1},
{1, 1, 0, 1, 0}
};
Output: 6
The largest rectangle's area is 6. The rectangle
can be formed by swapping column 2 with 3
The matrix after swapping will be
0 0 1 1 0
0 0 1 1 1
1 0 1 1 0

Input: bool mat[R][C] = { {0, 1, 0, 1, 0},


{0, 1, 1, 1, 1},
{1, 1, 1, 0, 1},
{1, 1, 1, 1, 1}
};
Output: 9

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

Time complexity of this step is O(R*C)


Step 2: Sort the rows in non-increasing fashion. After sorting step the matrix hist[][] would
be

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.

// C++ program to find the largest rectangle of 1's with swapping


// of columns allowed.
#include <bits/stdc++.h>
#define R 3
#define C 5
  

713
Chapter 102. Find the largest rectangle of 1’s with swapping of columns allowed

using namespace std;


  
// Returns area of the largest rectangle of 1's
int maxArea(bool mat[R][C])
{
    // An auxiliary array to store count of consecutive 1's
    // in every column.
    int hist[R + 1][C + 1];
  
    // Step 1: Fill the auxiliary array hist[][]
    for (int i = 0; i < C; i++) {
        // First row in hist[][] is copy of first row in mat[][]
        hist[0][i] = mat[0][i];
  
        // Fill remaining rows of hist[][]
        for (int j = 1; j < R; j++)
            hist[j][i] = (mat[j][i] == 0) ? 0 : hist[j - 1][i] + 1;
    }
  
    // Step 2: Sort rows of hist[][] in non-increasing order
    for (int i = 0; i < R; i++) {
        int count[R + 1] = { 0 };
  
        // counting occurrence
        for (int j = 0; j < C; j++)
            count[hist[i][j]]++;
  
        // Traverse the count array from right side
        int col_no = 0;
        for (int j = R; j >= 0; j--) {
            if (count[j] > 0) {
                for (int k = 0; k < count[j]; k++) {
                    hist[i][col_no] = j;
                    col_no++;
                }
            }
        }
    }
  
    // Step 3: Traverse the sorted hist[][] to find maximum area
    int curr_area, max_area = 0;
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            // Since values are in decreasing order,
            // The area ending with cell (i, j) can
            // be obtained by multiplying column number
            // with value of hist[i][j]
            curr_area = (j + 1) * hist[i][j];

714
Chapter 102. Find the largest rectangle of 1’s with swapping of columns allowed

            if (curr_area > max_area)


                max_area = curr_area;
        }
    }
    return max_area;
}
  
// Driver program
int main()
{
    bool mat[R][C] = { { 0, 1, 0, 1, 0 },
                       { 0, 1, 0, 1, 1 },
                       { 1, 1, 0, 1, 0 } };
    cout << "Area of the largest rectangle is " << maxArea(mat);
    return 0;
}

Output:

Area of the largest rectangle is 6

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

Find the longest path in a


matrix with given constraints

Find the longest path in a matrix with given constraints - GeeksforGeeks


Given a n*n matrix where all numbers are distinct, find the maximum length path (starting
from any cell) such that all cells along the path are in increasing order with a difference of
1.
We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1)
or (i-1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1.
Example:

Input: mat[][] = {{1, 2, 9}


{5, 3, 8}
{4, 6, 7}}
Output: 4
The longest path is 6-7-8-9.

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

          //  Update result if needed


          result = max(result, dp[i][j]);
       }
     }
  
     return result;
}
  
// Driver program
int main()
{
   int  mat[n][n] = {{1, 2, 9},
                    {5, 3, 8},
                    {4, 6, 7}};
   cout << "Length of the longest path is "
        << finLongestOverAll(mat);
   return 0;
}

Java

// Java program to find the longest path in a matrix


// with given constraints
  
class GFG 
{
    public static int n = 3;
      
    // Function that returns length of the longest path 
    // beginning with mat[i][j]
    // This function mainly uses lookup table dp[n][n]
    static int findLongestFromACell(int i, int j, int mat[][], int dp[][])
    {
        // 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);

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:

Length of the longest path is 4

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

Find the mean vector of a


Matrix

Find the mean vector of a Matrix - GeeksforGeeks


Given a matrix of size M x N, the task is to find the Mean Vector of the given matrix.
Examples:

Input : mat[][] = {{1, 2, 3},


{4, 5, 6},
{7, 8, 9}}
Output : Mean Vector is [4 5 6]
Mean of column 1 is (1 + 4 + 7) / 3 = 4
Mean of column 2 is (2 + 5 + 8) / 3 = 5
Mean of column 3 is (3 + 6 + 9) / 3 = 6

Input : mat[][] = {{2, 4},


{6, 8}}
Output : Mean Vector is [4 6]
Mean of column 1 is (2 + 6) / 2 = 4
Mean of column 2 is (4 + 8) / 2 = 6

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 :

[mean(length) mean(breadth) mean(height)]

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++

// C++ program to find mean vector


// of given matrix
#include <bits/stdc++.h>
using namespace std;
#define rows 3
#define cols 3
  
// Function to find mean vector
void meanVector(int mat[rows][cols])
{
    cout << "[ ";
  
    // 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;
        cout << mean << " ";
    }
  
    cout << "]";
}
  
// Drivers code
int main()
{
  
    int mat[rows][cols] = { { 1, 2, 3 },
                            { 4, 5, 6 },
                            { 7, 8, 9 } };
  
    meanVector(mat);
  
    return 0;
}

722
Chapter 104. Find the mean vector of a Matrix

Java

// Java program to find 


// mean vector of given matrix
import java.io.*;
  
class GFG 
{
static int rows = 3;
static int cols = 3;
  
// Function to 
// find mean vector
static void meanVector(int mat[][])
{
    System.out.print("[ ");
  
    // 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;
        System.out.print((int)mean + " ");
    }
  
    System.out.print("]");
}
  
// Driver code
public static void main (String[] args) 
{
    int mat[][] = {{1, 2, 3},
                   {4, 5, 6},
                   {7, 8, 9}};
  
    meanVector(mat);

723
Chapter 104. Find the mean vector of a Matrix

}
}
  
// This code is contributed
// by anuj_67.

Python3

# Python3 program to find 


# mean vector of given 
# matrix
rows = 3;
cols = 3;
  
# Function to
# find mean vector
def meanVector(mat):
    print("[ ", end = "");
  
    # loop to traverse
    # each column
    for i in range(rows):
          
        # to calculate
        # mean of each row
        mean = 0.00;
  
        # to store sum of 
        # elements of a column
        sum = 0;
  
        for j in range(cols):
            sum = sum + mat[j][i];
  
        mean = int(sum /rows);
        print(mean, end = " ");
  
    print("]");
  
# Driver Code
mat = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]];
  
meanVector(mat);
  
# This code is contributed
# by mits

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 ]

Time Complexity: O(rows * cols)


Improved By : vt_m, Mithun Kumar

Source

https://www.geeksforgeeks.org/find-mean-vector-matrix/

727
Chapter 105

Find the number of islands | Set


1 (Using DFS)

Find the number of islands | Set 1 (Using DFS) - GeeksforGeeks


Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an
island. For example, the below matrix contains 5 islands
Example:

Input : mat[][] = {{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}
Output : 5

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++

// Program to count islands in boolean 2D matrix


#include <stdio.h>
#include <string.h>
#include <stdbool.h>

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)

                DFS(M, i, j, visited);     // Visit all cells in this island.


                ++count;                   // and increment island count
            }
  
    return count;
}
  
// Driver program to test above function
int main()
{
    int M[][COL]= {  {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}
    };
  
    printf("Number of islands is: %d\n", countIslands(M));
  
    return 0;
}

Java

// Java program to count islands in boolean 2D matrix


import java.util.*;
import java.lang.*;
import java.io.*;
  
class Islands
{
    //No of rows and columns
    static final int ROW = 5, COL = 5;
  
    // A function to check if a given cell (row, col) can
    // be included in DFS
    boolean isSafe(int M[][], int row, int col,
                   boolean 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

731
Chapter 105. Find the number of islands | Set 1 (Using DFS)

    void DFS(int M[][], int row, int col, boolean 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], col + colNbr[k], visited);
    }
  
    // The main function that returns count of islands in a given
    //  boolean 2D matrix
    int countIslands(int M[][])
    {
        // Make a bool array to mark visited cells.
        // Initially all cells are unvisited
        boolean visited[][] = new boolean[ROW][COL];
  
  
        // 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]==1 && !visited[i][j]) // If a cell with
                {                                 // value 1 is not
                    // visited yet, then new island found, Visit all
                    // cells in this island and increment island count
                    DFS(M, i, j, visited);
                    ++count;
                }
  
        return count;
    }
  
    // Driver method
    public static void main (String[] args) throws java.lang.Exception
    {
        int M[][]=  new int[][] {{1, 1, 0, 0, 0},
                                 {0, 1, 0, 0, 1},
                                 {1, 0, 0, 1, 1},
                                 {0, 0, 0, 0, 0},

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

# Program to count islands in boolean 2D matrix


class Graph:
  
    def __init__(self, row, col, g):
        self.ROW = row
        self.COL = col
        self.graph = g
  
    # A function to check if a given cell 
    # (row, col) can be included in DFS
    def isSafe(self, i, j, visited):
        # row number is in range, column number
        # is in range and value is 1 
        # and not yet visited
        return (i >= 0 and i < self.ROW and 
                j >= 0 and j < self.COL and 
                not visited[i][j] and self.graph[i][j])
              
  
    # A utility function to do DFS for a 2D 
    # boolean matrix. It only considers
    # the 8 neighbours as adjacent vertices
    def DFS(self, i, j, visited):
  
        # These arrays are used to get row and 
        # column numbers of 8 neighbours 
        # of a given cell
        rowNbr = [-1, -1, -1,  0, 0,  1, 1, 1];
            colNbr = [-1,  0,  1, -1, 1, -1, 0, 1];
          
        # Mark this cell as visited
        visited[i][j] = True
  
        # Recur for all connected neighbours
        for k in range(8):
            if self.isSafe(i + rowNbr[k], j + colNbr[k], visited):
                self.DFS(i + rowNbr[k], j + colNbr[k], visited)
  
  

733
Chapter 105. Find the number of islands | Set 1 (Using DFS)

    # The main function that returns


    # count of islands in a given boolean
    # 2D matrix
    def countIslands(self):
        # Make a bool array to mark visited cells.
        # Initially all cells are unvisited
        visited = [[False for j in range(self.COL)]for i in range(self.ROW)]
  
        # Initialize count as 0 and travese 
        # through the all cells of
        # given matrix
        count = 0
        for i in range(self.ROW):
            for j in range(self.COL):
                # If a cell with value 1 is not visited yet, 
                # then new island found
                if visited[i][j] == False and self.graph[i][j] ==1:
                    # Visit all cells in this island 
                    # and increment island count
                    self.DFS(i, j, visited)
                    count += 1
  
        return count
  
  
graph = [[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]]
  
  
row = len(graph)
col = len(graph[0])
  
g= Graph(row, col, graph)
  
print "Number of islands is:"
print g.countIslands()
  
#This code is contributed by Neelam Yadav

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)

                       col + colNbr[k], visited);


    }
  
    // The main function that 
    // returns count of islands 
    // in a given boolean 2D matrix
    static int countIslands(int [,]M)
    {
        // Make a bool array to 
        // mark visited cells.
        // Initially all cells
        // are unvisited
        bool [,]visited = new bool[ROW, COL];
  
  
        // 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] == 1 && 
                    !visited[i, j]) 
                {    
                    // If a cell with value 1 is not
                    // visited yet, then new island 
                    // found, Visit all cells in this
                    // island and increment island count
                    DFS(M, i, j, visited);
                    ++count;
                }
  
        return count;
    }
  
    // Driver Code
    public static void Main ()
    {
        int [,]M = new int[,] {{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}};
        Console.Write("Number of islands is: " + 
                               countIslands(M));
    }

  

736
Chapter 105. Find the number of islands | Set 1 (Using DFS)

// This code is contributed 


// by shiv_bhakt.

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)

    // Recur for all 


    // connected neighbours
    for ($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
function countIslands(&$M)
{
    global $ROW, $COL;
      
    // Make a bool array to 
    // mark visited cells. 
    // Initially all cells 
    // are unvisited
    $visited = array(array());
  
    // Initialize count as 0 and
    // travese through the all 
    // cells of given matrix
    $count = 0;
    for ($i = 0; $i < $ROW; ++$i)
        for ($j = 0; $j < $COL; ++$j)
            if ($M[$i][$j] && 
                 !isset($visited[$i][$j])) // If a cell with value 1
            {                               // is not visited yet, 
                DFS($M, $i, $j, $visited); // then new island found 
                ++$count;                   // Visit all cells in this 
            }                               // island and increment 
                                           // island count.
  
    return $count;
}
  
// Driver Code
$M = array(array(1, 1, 0, 0, 0),
           array(0, 1, 0, 0, 1),
           array(1, 0, 0, 1, 1),
            array(0, 0, 0, 0, 0),
           array(1, 0, 1, 0, 1));
  
echo "Number of islands is: ",
            countIslands($M);

738
Chapter 105. Find the number of islands | Set 1 (Using DFS)

  
// This code is contributed 
// by ChitraNayal 
?>

Output:

Number of islands is: 5

Time complexity: O(ROW x COL)


Find the number of Islands | Set 2 (Using Disjoint Set)
Reference:
http://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29
Improved By : shiv_bhakt, ChitraNayal

Source

https://www.geeksforgeeks.org/find-number-of-islands/

739
Chapter 106

Find the row with maximum


number of 1s

Find the row with maximum number of 1s - GeeksforGeeks


Given a boolean 2D array, where each row is sorted. Find the row with the maximum
number of 1s.

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++

// CPP program to find the row


// with maximum number of 1s

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

// Java program to find the row


// with maximum number of 1s
import java.io.*;
  
class GFG {
    static int R = 4, C = 4;
    // Function to find the index of first index
    // of 1 in a boolean array arr[] 
    static int first(int 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;
    }
  

742
Chapter 106. Find the row with maximum number of 1s

    // Function that returns index of row


    // with maximum number of 1s.
    static int rowWithMax1s(int mat[][])
    {
        // 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;
            }
        }
  
        return max_row_index;
    }
    // Driver Code
    public static void main(String[] args)
    {
        int mat[][] = { { 0, 0, 0, 1 },
                        { 0, 1, 1, 1 },
                        { 1, 1, 1, 1 },
                        { 0, 0, 0, 0 } };
        System.out.println("Index of row with maximum 1s is "
                                            + rowWithMax1s(mat));
    }
}
  
// This code is contributed by 'Gitanjali'.

Python 3

# Python3 program to find the row


# with maximum number of 1s
  
# Function to find the index
# of first index of 1 in a 
# boolean array arr[] 
def first( arr, low, high):
    if high >= low:
          
        # Get the middle index 
        mid = low + (high - low)//2
  

743
Chapter 106. Find the row with maximum number of 1s

        # Check if the element at 


        # middle index is first 1
        if (mid == 0 or arr[mid - 1] == 0) and arr[mid] == 1:
            return mid
  
        # If the element is 0, 
        # recur for right side
        elif 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. 
def rowWithMax1s( mat):
      
    # Initialize max values
    R = len(mat)
    C = len(mat[0])
    max_row_index = 0
    max = -1
      
    # Traverse for each row and 
    # count number of 1s by finding
    #  the index of first 1
    for i in range(0, R):
        index = first (mat[i], 0, C - 1)
        if index != -1 and C - index > max:
            max = C - index
            max_row_index = i
  
    return max_row_index
  
# Driver Code
mat = [[0, 0, 0, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 0, 0, 0]]
print ("Index of row with maximum 1s is", 
      rowWithMax1s(mat))
  
# This code is contributed 
# by shreyanshi_arun 

744
Chapter 106. Find the row with maximum number of 1s

Output:

Index of row with maximum 1s is 2

Time Complexity: O(mLogn) where m is number of rows and n is number of columns in


matrix.
The above solution can be optimized further. Instead of doing binary search in every
row, we first check whether the row has more 1s than max so far. If the row has more 1s,
then only count 1s in the row. Also, to count 1s in a row, we don’t do binary search in
complete row, we do search in before the index of last max.
Following is an optimized version of the above solution.

// 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;
}

Thanks to Tylor, Ankan and Palash for their inputs.

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

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

Method 1 (Naive Approach) :


Generate matrix A and B and find the sum. Then traverse the main diagnol and find the
sum.
Below is the implementation of this approach:

C++

// C++ program to find


// trace of matrix formed by
// adding Row-major and
// Column-major order of same matrix
#include <bits/stdc++.h>
using namespace std;
  
// Return the trace of
// sum of row-major matrix
// and column-major matrix
int trace(int n, int m)
{
  
    int A[n][m], B[n][m], C[n][m];    
  
    // Generating the matrix A
    int cnt = 1;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            A[i][j] = cnt;
            cnt++;
        }    
  
    // Generating the matrix A
    cnt = 1;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) {
            B[j][i] = cnt;
            cnt++;
        }
  
    // Finding sum of matrix A and matrix B
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            C[i][j] = A[i][j] + B[i][j];    

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

// Java program to find


// trace of matrix formed by
// adding Row-major and
// Column-major order of same matrix
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];
        int C[][] = new int[n][m];
      
        // Generating the matrix A
        int cnt = 1;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                A[i][j] = cnt;
                cnt++;
            } 
      
        // Generating the matrix A
        cnt = 1;
        for (int i = 0; i < n; i++)

750
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix

            for (int j = 0; j < m; j++) {


                B[j][i] = cnt;
                cnt++;
            }
      
        // Finding sum of matrix A and matrix B
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                C[i][j] = A[i][j] + B[i][j]; 
      
        // 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;
    }
      
    // Driver code 
    public static void main (String[] args)
    {
        int N = 3, M = 3;
          
        System.out.println(trace(N, M));
    }
}
  
// This code is contributed by Anant Agarwal.

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

        int[, ] C = new int[n, m];


  
        // Generating the matrix A
        int cnt = 1;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                A[i, j] = cnt;
                cnt++;
            }
  
        // Generating the matrix A
        cnt = 1;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                B[j, i] = cnt;
                cnt++;
            }
  
        // Finding sum of matrix A and matrix B
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                C[i, j] = A[i, j] + B[i, j];
  
        // 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;
    }
  
    // Driver code
    public static void Main()
    {
        int N = 3, M = 3;
        Console.WriteLine(trace(N, M));
    }
}
  
// This code is contributed by vt_m.

Output :

30

752
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix

Time Complexity: O(N*M).


Method 2 (efficient approach) :
Basically, we need to find the sum of main diagonal of the first matrix A and main diagonal
of the second matrix B.
Let’s take an example, N = 3, M = 4.
Therefore, Row-major matrix will be,

1 2 3 4
A = 5 6 7 8
9 10 11 12

So, we need the sum of 1, 6, 11.


Observe, it form an Arithmetic Progression with constant difference of number of column,
M.
Also, first element is always 1. So, AP formed in case of Row-major matrix is 1, 1+(M+1),
1+2*(M+1), ….. consisting of N (number of rows) elements. And we know,
Sn = (n * (a1 + an ))/2
So, n = R, a1 = 1, an = 1 + (R – 1)*(M+1).
Similarly, in case of Column-major, AP formed will be 1, 1+(N+1), 1+2*(N+1), …..
So, n = R, a1 = 1, an = 1 + (R – 1)*(N+1).
Below is the implementation of this approach:

C++

// C++ program to find trace of matrix formed


// by adding Row-major and Column-major order
// of same matrix
#include <bits/stdc++.h>
using namespace std;
  
// Return sum of first n integers of an AP
int sn(int n, int an)
{
    return (n * (1 + an)) / 2;
}
  
// Return the trace of sum of row-major matrix
// and column-major matrix
int trace(int n, int m)
{
    // Finding nth element in
    // AP in case of Row major matrix.
    int an = 1 + (n - 1) * (m + 1);
  

753
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix

    // Finding sum of first n integers


    // of AP in case of Row major matrix
    int rowmajorSum = sn(n, an);
  
    // Finding nth element in AP
    // in case of Row major matrix
    an = 1 + (n - 1) * (n + 1);
  
    // Finding sum of first n integers
    // of AP in case of Column major matrix
    int colmajorSum = sn(n, an);
  
    return rowmajorSum + colmajorSum;
}
  
// Driven Program
int main()
{
    int N = 3, M = 3;
    cout << trace(N, M) << endl;
    return 0;
}

Java

// Java program to find trace of matrix formed


// by adding Row-major and Column-major order
// of same matrix
import java.io.*;
  
public class GFG {
  
    // Return sum of first n integers of an AP
    static int sn(int n, int an)
    {
        return (n * (1 + an)) / 2;
    }
  
    // Return the trace of sum of row-major matrix
    // and column-major matrix
    static int trace(int n, int m)
    {
        // Finding nth element in
        // AP in case of Row major matrix.
        int an = 1 + (n - 1) * (m + 1);
  
        // Finding sum of first n integers
        // of AP in case of Row major matrix

754
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix

        int rowmajorSum = sn(n, an);


  
        // Finding nth element in AP
        // in case of Row major matrix
        an = 1 + (n - 1) * (n + 1);
  
        // Finding sum of first n integers
        // of AP in case of Column major matrix
        int colmajorSum = sn(n, an);
  
        return rowmajorSum + colmajorSum;
    }
  
    // Driven Program
    static public void main(String[] args)
    {
        int N = 3, M = 3;
        System.out.println(trace(N, M));
    }
}
  
// This code is contributed by vt_m.

Python3

# Python3 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
def sn(n, an):
    return (n * (1 + an)) / 2;
  
# Return the trace of sum
# of row-major matrix
# and column-major matrix
def 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

755
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix

    rowmajorSum = sn(n, an);


      
    # Finding nth element in AP
    # in case of Row major matrix
    an = 1 + (n - 1) * (n + 1);
      
    # Finding sum of first n 
    # integers of AP in case 
    # of Column major matrix
    colmajorSum = sn(n, an);
      
    return int(rowmajorSum + 
               colmajorSum);
      
# Driver Code
N = 3;
M = 3;
print(trace(N, M));
  
# This code is contributed mits

C#

// C# program to find trace of matrix formed


// by adding Row-major and Column-major order
// of same matrix
using System;
  
public class GFG {
  
    // Return sum of first n integers of an AP
    static int sn(int n, int an)
    {
        return (n * (1 + an)) / 2;
    }
  
    // Return the trace of sum of row-major matrix
    // and column-major matrix
    static int trace(int n, int m)
    {
        // Finding nth element in
        // AP in case of Row major matrix.
        int an = 1 + (n - 1) * (m + 1);
  
        // Finding sum of first n integers
        // of AP in case of Row major matrix
        int rowmajorSum = sn(n, an);
  

756
Chapter 107. Find trace of matrix formed by adding Row-major and Column-major order
of same matrix

        // Finding nth element in AP


        // in case of Row major matrix
        an = 1 + (n - 1) * (n + 1);
  
        // Finding sum of first n integers
        // of AP in case of Column major matrix
        int colmajorSum = sn(n, an);
  
        return rowmajorSum + colmajorSum;
    }
  
    // Driven Program
    static public void Main()
    {
        int N = 3, M = 3;
        Console.WriteLine(trace(N, M));
    }
}
  
// This code is contributed by vt_m.

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

    // Finding nth element in AP


    // in case of Row major matrix
    $an = 1 + ($n - 1) * ($n + 1);
  
    // Finding sum of first n integers
    // of AP in case of Column major matrix
    $colmajorSum = sn($n, $an);
  
    return $rowmajorSum + $colmajorSum;
}
      
    // Driver Code
    $N = 3;
    $M = 3;
    echo trace($N, $M),"\n";
  
// This code is contributed ajit
?>

Output :

30

Improved By : jit_t, Mithun Kumar

Source

https://www.geeksforgeeks.org/find-trace-matrix-formed-adding-row-major-column-major-order-matrix/

758
Chapter 108

Find unique elements in a


matrix

Find unique elements in a matrix - GeeksforGeeks


Given a matrix mat[][] having n rows and m columns. We need to find unique elements in
matrix i.e, those elements which are not repeated in the matrix or those elements whose
frequency is 1.
Examples:

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

Follow these steps to find unique element:


1. Create an empty hash table or dictionary.
2. Traverse through all the elements of the matrix
3. If element is present in the dictionary, then increment its count
4. Otherwise insert element with value = 1.
C++

// C++ program to find unique


// element in 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

// This code is contributed by Naman_Garg.

Java

// Java program to find unique


// element in matrix
class GFG
{
static int R = 4, C = 4;
  
// function that calculate 
// unique element
static void unique(int mat[][], 
                   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[] = new int [maximum + 1];
    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)
            System.out.print(i + " ");
            flag = 1;
              
    if(flag == 0)
    {
        System.out.println("No unique element " + 
                                "in the matrix");
    }
}
  
// Driver Code
public static void main(String args[])
{
    int mat[][] = {{1, 2, 3, 20},

761
Chapter 108. Find unique elements in a matrix

                   {5, 6, 20, 25},


                   {1, 3, 5, 6},
                   {6, 7, 8, 15}};
                      
    // function that calculate 
    // unique element
    unique(mat, R, C);
}
}
  
// This code is contributed
// by Arnab Kundu

Python3

# Python program to find unique


# element in matrix
  
def unique(mat, n, m):
      
    # Creating dictionary to count the 
    # frequency of each element 
    uniqueElementDict = {}
      
    # loops to traverse through the matrix 
    for i in range(n):
        for j in range(m):
            if mat[i][j] in uniqueElementDict:
                uniqueElementDict[mat[i][j]] += 1
            else:
                uniqueElementDict[mat[i][j]] = 1
      
    # Print all those keys whose count is 1
    for key in uniqueElementDict:
        if uniqueElementDict[key] == 1:
            print (key, end =" ")
  
# Driver Code
mat = [[ 1, 2, 3, 20], 
        [5, 6, 20, 25],
        [1, 3, 5, 6],
        [6, 7, 8, 15]]
n = 4
m = 4
unique(mat, n, m)

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

Find whether there is path


between two cells in matrix

Find whether there is path between two cells in matrix - GeeksforGeeks


Given N X N matrix filled with 1 , 0 , 2 , 3 . Find whether there is a path possible from
source to destination, traversing through blank cells only. You can traverse up, down, right
and left.

• A value of cell 1 means Source.


• A value of cell 2 means Destination.
• A value of cell 3 means Blank cell.
• A value of cell 0 means Blank Wall.

Note : there is only single source and single destination(sink).


Examples:

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

Asked in: Adobe Interview

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 :

Find source index in matrix , let we consider ( i , j )


After that Find path from source(1) to sink(2)
FindPathUtil ( M[][N] , i , j )

IF we seen M[i][j] == 0 (wall) ||


((i, j) is out of matrix index)
return false ;
IF we seen destination M[i][j] == 2
return true ;

Next move in path by traverse all 4 adjacent


cell of current cell
IF (FindPathUtil(M[][N], i+1, j) ||
FindPathUtil(M[][N], i-1, j) ||
FindPathUtil(M[][N], i, j+1) ||
FindPathUtil(M[][N], i, j-1));
return true ;

return false ;

Efficient solution (Graph)


The idea is to use Breadth First Search. Consider each cell as a node and each boundary
between any two adjacent cells be an edge. so total number of Node is N*N.

1. Create an empty Graph having N*N node ( Vertex ).


2. push all node into graph.
3. notedown source and sink vertex
4. Now Appling BFS to find is there is path between
to vertex or not in graph
IF Path found return true
Else return False

below c++ implementation of above idea

// c++ program to find path between two


// cell in matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
  
class Graph

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

        for (int j = 0 ; j < N; j++)


        {
            if (M[i][j] != 0)
            {
                // connect all 4 adjacent cell to
                // current cell
                if ( isSafe ( i , j+1 , M ) )
                    g.addEdge ( k , k+1 );
                if ( isSafe ( i , j-1 , M ) )
                    g.addEdge ( k , k-1 );
                if (j< N-1 && isSafe ( i+1 , j , M ) )
                    g.addEdge ( k , k+N );
                if ( i > 0 && isSafe ( i-1 , j , M ) )
                    g.addEdge ( k , k-N );
            }
  
            // source index
            if( M[i][j] == 1 )
                s = k ;
  
            // destination index
            if (M[i][j] == 2)
                d = k;
            k++;
        }
    }
  
    // find path Using BFS
    return g.BFS (s, d) ;
}
  
// driver program to check above function
int main()
{
    int  M[N][N] =    {{ 0 , 3 , 0 , 1 },
        { 3 , 0 , 3 , 3 },
        { 2 , 3 , 3 , 3 },
        { 0 , 3 , 3 , 3 }
    };
  
    (findPath(M) == true) ?
     cout << "Yes" : cout << "No" <<endl ;
  
    return 0;
}

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

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:

Input : a[][] = {{2, 3, 3},


{2, 3, 3},
{2, 2, 2}}
Output : 2
Explanation: A 2x2 matrix is formed from index
A0,1 to A1,2

Input : a[][] = {{9, 9, 9, 8},


{9, 9, 9, 6},
{9, 9, 9, 3},
{2, 2, 2, 2}
Output : 3
Explanation : A 3x3 matrix is formed from index
A0,0 to A2,2

Method I ( Naive approach )


We can easily find all the square submatrices in O(n3 ) time and check whether each subma-

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 }

If Ai, j is equal to {Ai-1, j, Ai, j-1, Ai-1, j-1},


all the three values:
DPi, j = min(DPi-1, j, DPi, j-1, DPi-1, j-1) + 1
Else
DPi, j = 1 // Matrix Size 1

The answer would be the maximum of all DPi, j's

Below is the implementation of above steps.

C++

// C++ program to find maximum K such that K x K


// is a submatrix with equal elements.
#include<bits/stdc++.h>
#define Row 6
#define Col 6
using namespace std;
  
// Returns size of the largest square sub-matrix
// with all same elements.
int largestKSubmatrix(int a[][Col])
{
    int dp[Row][Col];
    memset(dp, sizeof(dp), 0);
  
    int result = 0;
    for (int i = 0 ; i < Row ; i++)
    {
        for (int 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

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

// Java program to find maximum 


// K such that K x K is a 
// submatrix with equal elements.
class GFG 
{
    static int Row = 6, Col = 6;
      
    // Returns size of the largest 
    // square sub-matrix with

772
Chapter 110. Finding the maximum square sub-matrix with all equal elements

    // all same elements.


    static int largestKSubmatrix(int [][]a)
    {
        int [][]dp = new int [Row][Col];
        int result = 0;
        for (int i = 0 ; 
                 i < Row ; i++)
        {
            for (int 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
                {
                    // 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;
    }
  

773
Chapter 110. Finding the maximum square sub-matrix with all equal elements

    // Driver code


    public static void main(String[] args) 
    {
        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}};
  
        System.out.println(largestKSubmatrix(a));
  
    }
}
  
// This code is contributed
// by ChitraNayal

C#

// C# program to find maximum 


// K such that K x K is a
// submatrix with equal elements.
using System;
  
class GFG 
{
    static int Row = 6, Col = 6;
      
    // Returns size of the 
    // largest square sub-matrix
    // with all same elements.
    static int largestKSubmatrix(int[,] a)
    {
        int[,] dp = new int [Row, Col];
        int result = 0;
        for (int i = 0 ; i < Row ; i++)
        {
            for (int 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;
  

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

# Python 3 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.
def largestKSubmatrix(a):
    dp = [[0 for x in range(Row)]
             for y in range(Col)]
  
    result = 0
    for i in range(Row ):
        for j in range(Col):
              
            # If elements is at top 
            # row or first column, 
            # it wont form a square
            # matrix's bottom-right
            if (i == 0 or j == 0):
                dp[i][j] = 1
  
            else:
                  
                # Check if adjacent 
                # elements are equal
                if (a[i][j] == a[i - 1][j] and
                    a[i][j] == a[i][j - 1] and
                    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])
              

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

                // 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;
}
  
// Driver Code
$a = array(array(2, 2, 3, 3, 4, 4),
           array(5, 5, 7, 7, 7, 4),
           array(1, 2, 7, 7, 7, 4),
           array(4, 4, 7, 7, 7, 4),
           array(5, 5, 5, 1, 2, 7),
           array(8, 7, 9, 4, 4, 4));
  
echo largestKSubmatrix($a);
  
// This code is contributed
// by ChitraNayal
?>

Output:

Time Complexity : O(Row * Col)


Auxiliary Space : O(Row * Col)
Improved By : ChitraNayal

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

Flood fill Algorithm – how to


implement fill() in paint?

Flood fill Algorithm - how to implement fill() in paint? - GeeksforGeeks


In MS-Paint, when we take the brush to a pixel and click, the color of the region of that
pixel is replaced with a new selected color. Following is the problem statement to do this
task.
Given a 2D screen, location of a pixel in the screen and a color, replace color of the given
pixel and all adjacent same colored pixels with the given color.
Example:

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},
};

Flood Fill Algorithm:


The idea is simple, we first replace the color of current pixel, then recur for 4 surrounding
points. The following is detailed algorithm.

// A recursive function to replace previous color 'prevC' at '(x, y)'


// and all surrounding pixels of (x, y) with new color 'newC' and
floodFil(screen[M][N], x, y, prevC, newC)
1) If x or y is outside the screen, then return.
2) If color of screen[x][y] is not same as prevC, then return
3) Recur for north, south, east 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);

The following is C++ implementation of above algorithm.

// A C++ program to implement flood fill algorithm


#include<iostream>
using namespace std;
  
// Dimentions of paint screen
#define M 8
#define N 8
  
// A recursive function to replace previous color 'prevC' at  '(x, y)' 
// and all surrounding pixels of (x, y) with new color 'newC' and
void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC)
{
    // Base cases
    if (x < 0 || x >= M || y < 0 || y >= N)
        return;
    if (screen[x][y] != prevC)
        return;
  
    // Replace the color at (x, y)
    screen[x][y] = newC;

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:

Updated screen after call to floodFill:


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 3 3 3 3 0 1 0
1 1 1 3 3 0 1 0

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

Form coils in a matrix

Form coils in a matrix - GeeksforGeeks


Given a positive integer n that represents dimensions of a 4n x 4n matrix with values from
1 to n filled from left to right and top to bottom. Form two coils from matrix and print the
coils.
Examples:

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++

// C++ program to print 2 coils of a


// 4n x 4n matrix.
#include<iostream>
using namespace std;
  
// Print coils in a matrix of size 4n x 4n 
void printCoils(int n)
{
    // Number of elements in each coil
    int m = 8*n*n;
  
    // Let us fill elements in coil 1.
    int coil1[m];
  
    // First element of coil1
    // 4*n*2*n + 2*n;
    coil1[0] = 8*n*n + 2*n;
    int curr = coil1[0];
  
    int nflg = 1, step = 2;
  
    // Fill remaining m-1 elements in coil1[]
    int index = 1;
    while (index < m)
    {
        // Fill elements of current step from
        // down to up
        for (int 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 (int i=0; i<step; i++)
        {
            curr = coil1[index++] = curr + nflg;
            if (index >= m)
                break;
        }
        nflg = nflg*(-1);

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

// Java program to print 2 coils 


// of a 4n x 4n matrix.
  
class GFG {
      
    // Print coils in a matrix of size 4n x 4n
    static void printCoils(int n) 
    {
        // Number of elements in each coil
        int m = 8 * n * n;
      
        // Let us fill elements in coil 1.
        int coil1[] = new int[m];
      
        // First element of coil1
        // 4*n*2*n + 2*n;
        coil1[0] = 8 * n * n + 2 * n;
        int curr = coil1[0];
      
        int nflg = 1, step = 2;
      

786
Chapter 112. Form coils in a matrix

        // Fill remaining m-1 elements in coil1[]


        int index = 1;
        while (index < m)
        {
            // Fill elements of current step from
            // down to up
            for (int 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 (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
        System.out.print("Coil 1 : ");
          
        for (int i = 0; i < 8 * n * n; i++)
            System.out.print(coil1[i] + " ");
          
        System.out.print("\nCoil 2 : ");
          
        for (int i = 0; i < 8 * n * n; i++)
            System.out.print(coil2[i] + " ");
    }
      
    // Driver code
    public static void main(String[] args)

787
Chapter 112. Form coils in a matrix

    {
        int n = 1;
        printCoils(n);
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program to print 2 coils 


// of a 4n x 4n matrix.
using System;
  
class GFG {
      
    // Print coils in a matrix of
    // size 4n x 4n
    static void printCoils(int n) 
    {
          
        // Number of elements in
        // each coil
        int m = 8 * n * n;
      
        // Let us fill elements in
        // coil 1.
        int [] coil1 = new int[m];
      
        // First element of coil1
        // 4*n*2*n + 2*n;
        coil1[0] = 8 * n * n + 2 * n;
        int curr = coil1[0];
      
        int nflg = 1, step = 2;
      
        // Fill remaining m-1 elements
        // in coil1[]
        int index = 1;
        while (index < m)
        {
              
            // Fill elements of current
            // step from down to up
            for (int i = 0; i < step; i++) 
                {
                    // Next element from 
                    // current element

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

Freivald’s Algorithm to check if


a matrix is product of two

Freivald’s Algorithm to check if a matrix is product of two - GeeksforGeeks


Given three matrices A, B and C, find if C is a product of A and B.
Examples:

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

Freivalds’ algorithm is a probabilistic randomized algorithm that works in time O(n2 )


with high probability. In O(kn2 ) time the algorithm can verify a matrix product with
probability of failure less than 2-k . Since the output is not always correct, it is a Monte
Carlo randomized algorithm.
Steps :

1. Generate an n × 1 random 0/1 vector r�.


2. Compute P� = A × (Br)� – Cr�.
3. Return true if P� = ( 0, 0, …, 0 )T , return false otherwise.

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++

// CPP code to implement Freivald’s Algorithm


#include <bits/stdc++.h>
using namespace std;
  
#define N 2
  
// Function to check if ABx = Cx
int freivald(int a[][N], int b[][N], int c[][N])
{
    // Generate a random vector
    bool r[N];
    for (int i = 0; i < N; i++)
        r[i] = random() % 2;
  
    // Now comput B*r for evaluating
    // expression A * (B*r) - (C*r)
    int br[N] = { 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[N] = { 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[N] = { 0 };

794
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two

    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)
            false;
  
    return true;
}
  
// Runs k iterations Freivald. The value
// of k determines accuracy. Higher value
// means higher accuracy.
bool isProduct(int a[][N], int b[][N],
               int c[][N], int k)
{
    for (int i=0; i<k; i++)
        if (freivald(a, b, c) == false)
            return false;
    return true;
}
  
// Driver code
int main()
{
    int a[N][N] = { { 1, 1 }, { 1, 1 } };
    int b[N][N] = { { 1, 1 }, { 1, 1 } };
    int c[N][N] = { { 2, 2 }, { 2, 2 } };
    int k = 2;
    if (isProduct(a, b, c, k))
        printf("Yes");
    else
        printf("No");
    return 0;
}

Java

// Java code to implement 


// Freivald's Algorithm
import java.io.*;
import java.util.*;
import java.math.*;
  
class GFG {

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

                                 int c[][], int k)


    {
        for (int i = 0; i < k; i++)
            if (freivald(a, b, c) == false)
                return false;
        return true;
    }
  
    // Driver code
    public static void main(String args[])
    {
        int a[][] = { { 1, 1 }, { 1, 1 } };
        int b[][] = { { 1, 1 }, { 1, 1 } };
        int c[][] = { { 2, 2 }, { 2, 2 } };
        int k = 2;
        if (isProduct(a, b, c, k))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
/*This code is contributed by Nikita Tiwari.*/

Python3

# Python3 code to implement Freivald’s Algorithm


from random import *
N = 2
  
# Function to check if ABx = Cx
def freivald(a, b, c) :
      
    # Generate a random vector
    r = [0] * N
      
    for i in range(0, N) :
        r[i] = (int)(random()) % 2
  
    # Now comput B*r for evaluating
    # expression A * (B*r) - (C*r)
    br = [0] * N
      
    for i in range(0, N) :
        for j in range(0, N) :
            br[i] = br[i] + b[i][j] * r[j]
  
    # Now comput C*r for evaluating

797
Chapter 113. Freivald’s Algorithm to check if a matrix is product of two

    # expression A * (B*r) - (C*r)


    cr = [0] * N
    for i in range(0, N) :
        for j in range(0, N) :
            cr[i] = cr[i] + c[i][j] * r[j]
  
    # Now comput A* (B*r) for evaluating
    # expression A * (B*r) - (C*r)
    axbr = [0] * N
    for i in range(0, N) :
        for j in range(0, N) :
            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 i in range(0, N) :
        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.
def isProduct(a, b, c, k) :
      
    for i in range(0, k) :
        if (freivald(a, b, c) == False) :
            return False
    return True
  
# Driver code
a = [ [ 1, 1 ], [ 1, 1 ] ]
b = [ [ 1, 1 ], [ 1, 1 ] ]
c = [ [ 2, 2 ], [ 2, 2 ] ]
k = 2
  
if (isProduct(a, b, c, k)) :
    print("Yes")
else :
    print("No")
  
# This code is contributed by Nikita Tiwari

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

    // A * (B*r) - (C*r)


    for ($i = 0; $i < $N; $i++) 
    {
        for ($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 ($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.
function isProduct($a, $b, $c, $k)
{
    for ($i = 0; $i < $k; $i++)
        if (freivald($a, 
                     $b, $c) == false)
            return false;
    return true;
}
  
// Driver code
$a = array(array(1, 1), 
           array(1, 1));
$b = array(array(1, 1), 
           array(1, 1));
$c = array(array(2, 2), 
           array(2, 2));
$k = 2;
if (isProduct($a, $b, 
              $c, $k))
    echo ("Yes");
else
    echo ("No");
      
// This code is contributed 
// by Manish Shaw(manishshaw1)

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

Frequencies of even and odd


numbers in a matrix

Frequencies of even and odd numbers in a matrix - GeeksforGeeks


Given a matrix of order m*n then the task is to find the frequency of even and odd numbers
in matrix
Examples:

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

// C++ Program to Find the frequency


// of even and odd numbers in a matrix
#include<bits/stdc++.h>
using namespace std;
  

804
Chapter 114. Frequencies of even and odd numbers in a matrix

#define MAX 100


  
// function for calculating frequency
void freq(int ar[][MAX], int m, int n)
{
    int even = 0, odd = 0;
      
    for (int i = 0; i < m; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            // modulo by 2 to check
            // even and odd
            if ((ar[i][j] % 2) == 0)
                ++even;
            else
                ++odd;
        }
    }
      
    // print Frequency of numbers
    printf(" Frequency of odd number = %d \n", odd);
    printf(" Frequency of even number = %d \n", even);
}
  
// Driver code
int main()
{
    int m = 3, n = 3;    
      
    int array[][MAX] = { { 1, 2, 3 },
                        { 4, 5, 6 },
                        { 7, 8, 9 } };
  
    freq(array, m, n);
    return 0;
}        

Java

// Java Program to Find the frequency


// of even and odd numbers in a matrix
  
class GFG {
static final int MAX = 100;
  
// function for calculating frequency
static void freq(int ar[][], int m, int n) {

805
Chapter 114. Frequencies of even and odd numbers in a matrix

    int even = 0, odd = 0;


  
    for (int i = 0; i < m; ++i) 
    {
        for (int j = 0; j < n; ++j)
        {
            // modulo by 2 to check
            // even and odd
            if ((ar[i][j] % 2) == 0)
                ++even;
            else
                ++odd;
    }
    }
  
    // print Frequency of numbers
    System.out.print(" Frequency of odd number =" +
                       odd + " \n");
    System.out.print(" Frequency of even number = " +
                       even + " \n");
}
  
// Driver code
public static void main(String[] args) {
    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 Anant Agarwal.

Python3

# Python Program to Find the frequency


# of even and odd numbers in a matrix
  
MAX=100
   
# Function for calculating frequency
def freq(ar, m, n):
    even = 0
    odd = 0
       
    for i in range(m):
        for j in range(n):
          

806
Chapter 114. Frequencies of even and odd numbers in a matrix

            # modulo by 2 to check


            # even and odd
            if ((ar[i][j] % 2) == 0):
                even += 1
            else:
                odd += 1
       
    # print Frequency of numbers
    print(" Frequency of odd number =", odd)
    print(" Frequency of even number =", even)
  
   
# Driver code
m = 3
n = 3    
       
array = [ [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ] ]
   
freq(array, m, n)
  
# This code is contributed
# by Anant Agarwal.

C#

// C# Program to Find the frequency


// of even and odd numbers in a matrix
using System;
  
class GFG 
{
    //static int MAX = 100;
      
    // function for calculating frequency
    static void freq(int [,]ar, int m, int n) 
    {
        int even = 0, odd = 0;
      
        for (int i = 0; i < m; ++i) 
        {
            for (int j = 0; j < n; ++j)
            {
                // modulo by 2 to check
                // even and odd
                if ((ar[i, j] % 2) == 0)
                    ++even;

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:

Frequency of odd number = 5


Frequency of even number = 4

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.

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++

// CPP program to print  given number of 1's, 


// 2's, 3's ....k's in  zig-zag way.
#include <bits/stdc++.h>
using namespace std;
  
// function that prints  given number of 1's, 
// 2's, 3's ....k's in zig-zag way.
void ZigZag(int rows, int columns, int numbers[])
{
    int k = 0;
      
    // two-dimensional array to store numbers. 
    int arr[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 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

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

// Java program to print given


// number of 1's, 2's, 3's ....k's 
// in zig-zag way.
import java.util.*;
import java.lang.*;
  
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
            {

813
Chapter 115. Given 1’s, 2’s, 3’s ……k’s print them in zig zag way.

                // for each column.


                for (int j=columns-1; j>=0 &&
                    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++)
                System.out.print(arr[i][j] + " ");
              
            System.out.println();
        }
    }
      
    // Driver function 
    public static void main(String argc[])
    {
        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 Sagar Shukla */

C#

// C# program to print given


// number of 1's, 2's, 3's ....k's 
// in zig-zag way.

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.

                // if array contains zero then 


                // increment index to make this 
                // next index.
                if ($numbers[$k]==0)
                    $k++;
            }
        }
    }
      
    // printing the stored elements.
    for($i = 0; $i < $rows;$i++)
    {
        for($j = 0; $j < $columns; $j++)
            echo $arr[$i][$j] , " ";
              
        echo "\n";
    }
}
  
    // Driver Code
    $rows = 4;
    $columns = 5;
    $Numbers = array(3, 4, 2, 2, 3, 1, 5);
    ZigZag($rows, $columns,$Numbers); 
      
// This code is contributed by anuj_67.
?>

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.

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:

Input: bool mat[n][n] = { {1, 0, 0, 0},


{1, 1, 1, 0},
{1, 1, 0, 0},
{1, 1, 1, 0},
};
Output: 0
All elements in 0'th row are 0 and all elements in
0'th column are 1. mat[0][0] is 1 (can be any value)

Input: bool mat[n][n] = {{0, 1, 1, 0, 1},


{0, 0, 0, 0, 0},
{1, 1, 1, 0, 0},
{1, 1, 1, 1, 0},
{1, 1, 1, 1, 1}};
Output: 1
All elements in 1'st row are 0 and all elements in
1'st column are 1. mat[1][1] is 0 (can be any value)

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.

Input: bool mat[n][n] = {{0, 1, 1, 0, 1},


{0, 0, 0, 0, 0},
{1, 1, 1, 0, 0},
{1, 0, 1, 1, 0},
{1, 1, 1, 1, 1}};
Output: -1
There is no k such that k'th row elements are 0 and
k'th column elements are 1.

Expected time complexity is O(n)


We strongly recommend you to minimize your browser and try this yourself
first.
A Simple Solution is check all rows one by one. If we find a row ‘i’ such that all elements
of this row are 0 except mat[i][i] which may be either 0 or 1, then we check all values in
column ‘i’. If all values are 1 in the column, then we return i. Time complexity of this
solution is O(n2 ).
An Efficient Solution can solve this problem in O(n) time. The solution is based on below
facts.
1) There can be at most one k that can be qualified to be an answer (Why? Note that if
k’th row has all 0’s probably except mat[k][k], then no column can have all 1�)s.
2) If we traverse the given matrix from a corner (preferably from top right and bottom left),
we can quickly discard complete row or complete column based on below rules.
….a) If mat[i][j] is 0 and i != j, then column j cannot be the solution.
….b) If mat[i][j] is 1 and i != j, then row i cannot be the solution.
Below is complete algorithm based on above observations.

1) Start from top right corner, i.e., i = 0, j = n-1.


Initialize result as -1.

2) Do following until we find the result or reach outside the matrix.

......a) If mat[i][j] is 0, then check all elements on left of j in current row.


.........If all elements on left of j are also 0, then set result as i. Note
.........that i may not be result, but if there is a result, then it must be i
.........(Why? we reach mat[i][j] after discarding all rows above it and all
.........columns on right of it)

.........If all left side elements of i'th row are not 0, them this row cannot
.........be a solution, increment i.

......b) If mat[i][j] is 1, then check all elements below i in current column.


.........If all elements below i are 1, then set result as j. Note that j may
......... not be result, but if there is a result, then it must be j

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.

3) If result is -1, return it.

4) Else check validity of result by checking all row and column


elements of result

Below is C++ implementation based on above idea.


C++

// 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’

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:

Input: mat[M][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'},
};
Output: mat[M][N] = {{'X', 'O', 'X', 'X', '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'},
};

Input: mat[M][N] = {{'X', 'X', 'X', 'X'}


{'X', 'O', 'X', 'X'}
{'X', 'O', 'O', 'X'}

825
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’

{'X', 'O', 'X', 'X'}


{'X', 'X', 'O', 'O'}
};

Input: mat[M][N] = {{'X', 'X', 'X', 'X'}


{'X', 'X', 'X', 'X'}
{'X', 'X', 'X', 'X'}
{'X', 'X', 'X', 'X'}
{'X', 'X', 'O', 'O'}
};

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.

mat[M][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'},
};

Step 1: Replace all ‘O’ with ‘-‘.

mat[M][N] = {{'X', '-', 'X', 'X', 'X', 'X'},


{'X', '-', 'X', 'X', '-', 'X'},
{'X', 'X', 'X', '-', '-', 'X'},
{'-', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', '-', 'X', '-'},
{'-', '-', 'X', '-', '-', '-'},
};

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’

mat[M][N] = {{'X', 'O', 'X', 'X', 'X', 'X'},


{'X', 'O', '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'},
};

Step 3: Replace all ‘-‘ with ‘X’.

mat[M][N] = {{'X', 'O', 'X', 'X', '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'},
};

The following is implementation of above algorithm.


C++

// A C++ program to replace all 'O's with 'X''s if surrounded by 'X'


#include<iostream>
using namespace std;
  
// Size of given matrix is M X N
#define M 6
#define N 6
  
  
// A recursive function to replace previous value 'prevV' at  '(x, y)'
// and all surrounding values of (x, y) with new value 'newV'.
void floodFillUtil(char mat[][N], 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)
    mat[x][y] = newV;
  
    // Recur for north, east, south and west
    floodFillUtil(mat, x+1, y, prevV, newV);

827
Chapter 117. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’

    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'
int replaceSurrounded(char mat[][N])
{
   // 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 program to test above function
int main()
{
    char mat[][N] =  {{'X', 'O', 'X', 'O', 'X', 'X'},
                     {'X', 'O', 'X', 'X', 'O', 'X'},
                     {'X', 'X', 'X', 'O', 'X', 'X'},
                     {'O', 'X', 'X', 'X', 'X', 'X'},
                     {'X', 'X', 'X', 'O', 'X', 'O'},
                     {'O', 'O', 'X', 'O', 'O', 'O'},
                    };
    replaceSurrounded(mat);

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

// A Java program to replace 


// all 'O's with 'X''s if 
// surrounded by 'X'
import java.io.*;
  
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)
        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);
    }

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’

                        {'X', 'X', 'X', 


                         'O', 'X', 'X'},
                        {'O', 'X', 'X',
                         'X', 'X', 'X'},
                        {'X', 'X', 'X',
                         'O', 'X', 'O'},
                        {'O', 'O', 'X',
                         'O', 'O', 'O'}};
                          
        replaceSurrounded(mat);
      
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
                System.out.print(mat[i][j] + " "); 
                  
            System.out.println("");
        }
    }
}
  
// This code is contributed 
// by shiv_bhakt

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’

    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 ()
    {
        char [,]mat = new char[,]
                        {{'X', 'O', 'X', 
                          'O', 'X', 'X'},
                         {'X', 'O', 'X', 
                          'X', 'O', 'X'},
                         {'X', 'X', 'X', 
                          'O', 'X', 'X'},
                         {'O', 'X', 'X',
                          'X', 'X', 'X'},
                         {'X', 'X', 'X',
                          'O', 'X', 'O'},
                         {'O', 'O', 'X',
                          'O', 'O', 'O'}};
                          
        replaceSurrounded(mat);
      
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
                Console.Write(mat[i, j] + " "); 
                  
            Console.WriteLine("");
        }
    }
}
  
// This code is contributed 
// by shiv_bhakt

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’

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:

Input: mat[N][N] = { {'X', 'O', 'X', 'X', 'X'},


{'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'O', 'X', 'O'},
{'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'O'},
};
Output: 3
The square submatrix starting at (1, 1) is the largest
submatrix surrounded by 'X'

Input: mat[M][N] = { {'X', 'O', 'X', 'X', 'X', 'X'},


{'X', 'O', 'X', 'X', 'O', 'X'},
{'X', 'X', 'X', 'O', 'O', 'X'},
{'X', 'X', 'X', 'X', 'X', 'X'},
{'X', 'X', 'X', 'O', 'X', 'O'},
};
Output: 4

837
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’

The square submatrix starting at (0, 2) is the largest


submatrix 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++

// A C++ program to find  the largest subsquare


// surrounded by 'X' in a given matrix of 'O' and 'X'

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

// A JAVA program to find the 


// largest subsquare surrounded 
// by 'X' in a given matrix of 
// 'O' and 'X'
import java.util.*;
  
class GFG 
{
    // Size of given 
    // matrix is N X N
    static int N = 6;
      

840
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’

    // A utility function to 


    // find minimum of two numbers
    static int getMin(int x, int y)
    { return (x < y) ? x : y; }
      
    // Returns size of maximum
    // size subsquare matrix
    // surrounded by 'X'
    static int findSubSquare(int mat[][])
    {
    int max = 0; // Initialize result
  
    // Initialize the left-top 
    // value in hor[][] and ver[][]
    int hor[][] = new int[N][N];
    int ver[][] = new int[N][N];
    hor[0][0] = ver[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 
    // subsquare 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 

841
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’

            // 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'.
  
            // 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 Code
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
          
        int mat[][] = {{'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'}};
            System.out.println(findSubSquare(mat));
    }
}
  
// This code is contributed

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’

    // bottommost corner element 


    // and find the largest 
    // subsquare with the help of
    // $hor and $ver
    for ($i = $GLOBALS['N'] - 1; $i >= 1; $i--)
    {
        for ($j = $GLOBALS['N'] - 1; $j >= 1; $j--)
        {
            // Find smaller of values in 
            // $hor and $ver A Square can 
            // only be made by taking 
            // smaller value
            $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'.
  
            // 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 Code
$mat = array(array('X', 'O', 'X', 'X', 'X', 'X'),
             array('X', 'O', 'X', 'X', 'O', 'X'),
             array('X', 'X', 'X', 'O', 'O', 'X'),
             array('O', 'X', 'X', 'X', 'X', 'X'),
             array('X', 'X', 'X', 'O', 'X', 'O'),

844
Chapter 118. Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’

             array('O', 'O', 'X', 'O', 'O', 'O'));


echo findSubSquare($mat);
  
// This code is contributed
// by ChitraNayal
?>

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

Given an n x n square matrix,


find sum of all sub-squares of
size k x k

Given an n x n square matrix, find sum of all sub-squares of size k x k - GeeksforGeeks


Given an n x n square matrix, find sum of all sub-squares of size k x k where k is smaller
than or equal to n.
Examples :

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++

// A simple C++ program to find sum of all subsquares of size k x k


#include <iostream>
using namespace std;
  
// Size of given matrix
#define n 5
  
// A simple function to find sum of all sub-squares of size k x k
// in a given square matrix of size n x n
void printSumSimple(int mat[][n], int k)
{
   // k must be smaller than or equal to n
   if (k > n) return;
  
   // row number of first cell in current sub-square of size k x k
   for (int i=0; i<n-k+1; i++)
   {
      // column of first cell in current sub-square of size k x k
      for (int j=0; j<n-k+1; j++)
      {
          // Calculate and print sum of current sub-square
          int sum = 0;
          for (int p=i; p<k+i; p++)
             for (int q=j; q<k+j; q++)
                 sum += mat[p][q];
           cout << sum << "  ";
      }
  
      // Line separator for sub-squares starting with next row
      cout << endl;
   }
}
  
// Driver program to test above function
int main()
{

847
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k

    int mat[n][n] = {{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},
                    };
    int k = 3;
    printSumSimple(mat, k);
    return 0;
}

Java

// A simple Java program to find sum of all 


// subsquares of size k x k
class GFG
{
      
    // Size of given matrix
    static final int n = 5;
      
    // A simple 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 printSumSimple(int mat[][], int k)
    {
  
        // k must be smaller than or 
        // equal to n
        if (k > n) return;
          
        // row number of first cell in 
        // current sub-square of size k x k
        for (int i = 0; i < n-k+1; i++)
        {
              
            // column of first cell in current 
            // sub-square of size k x k
            for (int j = 0; j < n-k+1; j++)
            {
                  
                // Calculate and print sum of 
                // current sub-square
                int sum = 0;
                for (int p = i; p < k+i; p++)
                    for (int q = j; q < k+j; q++)
                        sum += mat[p][q];
  

848
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k

                System.out.print(sum+ " ");


            }
          
            // Line separator for sub-squares 
            // starting with next row
            System.out.println();
        }
    }
      
    // Driver Program to test above function
    public static void main(String arg[])
    {
        int mat[][] = {{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}};
        int k = 3;
        printSumSimple(mat, k);
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// A simple C# program to find sum of all 


// subsquares of size k x k
using System;
  
class GFG
{
    // Size of given matrix
    static int n = 5;
      
    // A simple 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 printSumSimple(int [,]mat, int k)
    {
        // k must be smaller than or 
        // equal to n
        if (k > n) return;
          
        // row number of first cell in 
        // current sub-square of size k x k
        for (int i = 0; i < n-k+1; i++)
        {

849
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k

            // column of first cell in current 


            // sub-square of size k x k
            for (int j = 0; j < n-k+1; j++)
            {
                // Calculate and print sum of 
                // current sub-square
                int sum = 0;
                for (int p = i; p < k+i; p++)
                    for (int q = j; q < k+j; q++)
                        sum += mat[p,q];
  
                Console.Write(sum+ " ");
            }
          
            // Line separator for sub-squares 
            // starting with next row
            Console.WriteLine();
        }
    }
      
    // Driver Program to test above function
    public static void Main()
    {
        int [,]mat = {{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}};
        int k = 3;
        printSumSimple(mat, k);
    }
}
  
// This code is contributed by Sam007

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

function printSumSimple( $mat, $k)


{
    global $n;
      
    // k must be smaller than
    // or equal to n
    if ($k > $n) return;
      
    // row number of first cell in 
    // current sub-square of size
    // k x k
    for($i = 0; $i < $n - $k + 1; $i++)
    {
          
        // column of first cell in 
        // current sub-square of size
        // k x k
        for($j = 0; $j < $n - $k + 1; $j++)
        {
              
            // Calculate and print sum of
            // current sub-square
            $sum = 0;
            for ($p = $i; $p < $k + $i; $p++)
                for ($q = $j; $q < $k + $j; $q++)
                    $sum += $mat[$p][$q];
            echo $sum , " ";
        }
      
        // Line separator for sub-squares
        // starting with next row
        echo "\n";
    }
}
  
    // 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;
    printSumSimple($mat, $k);
  
// This code is contributed by anuj_67.
?>

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++

// An efficient C++ program to find sum of all subsquares of size k x k


#include <iostream>
using namespace std;
  
// Size of given matrix
#define 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
void printSumTricky(int mat[][n], 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[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

852
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k

       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];
      cout << sum << "  ";
  
      // 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]);
         cout << sum << "  ";
      }
  
      cout << endl;
   }
}
  
// Driver program to test above function
int main()
{
    int mat[n][n] = {{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},
                    };
    int k = 3;
    printSumTricky(mat, k);
    return 0;
}

Java

// An efficient Java program to find


// sum of all subsquares of size k x k
import java.io.*;

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

    // 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]);
        System.out.print(sum + " ");
    }
    System.out.println();
    }
}
  
// Driver program to test above function
public static void main(String[] args)
{
    int mat[][] = {{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},
                  };
    int k = 3;
    printSumTricky(mat, k);
}
}
  
// This code is contributed by vt_m.

C#

// An efficient C# program to find


// sum of all subsquares of size k x k
using System;
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

855
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k

        // 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];
                  
            Console.Write(sum + " ");
          
            // 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]);

856
Chapter 119. Given an n x n square matrix, find sum of all sub-squares of size k x k

                Console.Write(sum + " ");


            }
            Console.WriteLine();
        }
    }
      
    // Driver program to test above function
    public static void Main()
    {
        int [,]mat = {{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},
                    };
        int k = 3;
        printSumTricky(mat, k);
    }
}
  
// This code is contributed by nitin mittal.

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

Gold Mine Problem

Gold Mine Problem - GeeksforGeeks


Given a gold mine of n*m dimensions. Each field in this mine contains a positive integer
which is the amount of gold in tons. Initially the miner is at first column but can be at any
row. He can move only (right->,right up /,right down\) that is from a given cell, the miner
can move to the cell diagonally up towards the right or right or diagonally down towards
the right. Find out maximum amount of gold he can collect.
Examples:

Input : mat[][] = {{1, 3, 3},


{2, 1, 4},
{0, 6, 4}};
Output : 12
{(1,0)->(2,1)->(2,2)}

Input: mat[][] = { {1, 3, 1, 5},


{2, 2, 4, 1},
{5, 0, 2, 3},
{0, 6, 1, 2}};
Output : 16
(2,0) -> (1,1) -> (1,2) -> (0,3) OR
(2,0) -> (3,1) -> (2,2) -> (2,3)

Input : mat[][] = {{10, 33, 13, 15},


{22, 21, 04, 1},
{5, 0, 2, 3},
{0, 6, 14, 2}};
Output : 83

Source Flipkart Interview

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.

1. Amount of gold is positive, so we would like to cover maximum cells of maximum


values under given constraints.
2. In every move, we move one step toward right side. So we always end up in last
column. If we are at the last column, then we are unable to move right

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

// C++ program to solve Gold Mine problem


#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Returns maximum amount of gold that can be collected
// when journey started from first column and moves
// allowed are right, right-up and right-down
int getMaxGold(int gold[][MAX], int m, int n)
{
    // Create a table for storing intermediate results
    // and initialize all cells to 0. The first row of
    // goldMineTable gives the maximum gold that the miner
    // can collect when starts that row
    int goldTable[m][n];
    memset(goldTable, 0, sizeof(goldTable));
  
    for (int col=n-1; col>=0; col--)
    {
        for (int row=0; row<m; row++)
        {
            // Gold collected on going to the cell on the right(->)
            int right = (col==n-1)? 0: goldTable[row][col+1];
  
            // Gold collected on going to the cell to right up (/)
            int right_up = (row==0 || col==n-1)? 0:
                            goldTable[row-1][col+1];
  
            // Gold collected on going to the cell to right down (\)
            int right_down = (row==m-1 || col==n-1)? 0:

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

// Java program to solve Gold Mine problem


import java.util.Arrays;
  
class GFG {
      
    static final int MAX = 100;
      
    // Returns maximum amount of gold that 
    // can be collected when journey started 
    // from first column and moves allowed 
    // are right, right-up and right-down
    static int getMaxGold(int gold[][], 
                              int m, int n)
    {
          

862
Chapter 120. Gold Mine Problem

        // Create a table for storing 


        // intermediate results and initialize
        // all cells to 0. The first row of
        // goldMineTable gives the maximum 
        // gold that the miner can collect 
        // when starts that row
        int goldTable[][] = new int[m][n];
          
        for(int[] rows:goldTable)
            Arrays.fill(rows, 0);
      
        for (int col = n-1; col >= 0; col--)
        {
            for (int row = 0; row < m; row++)
            {
                  
                // Gold collected on going to 
                // the cell on the right(->)
                int right = (col == n-1) ? 0 
                        : goldTable[row][col+1];
      
                // Gold collected on going to 
                // the cell to right up (/)
                int right_up = (row == 0 ||
                               col == n-1) ? 0 :
                        goldTable[row-1][col+1];
      
                // Gold collected on going to 
                // the cell to right down (\)
                int right_down = (row == m-1 
                            || col == n-1) ? 0 :
                          goldTable[row+1][col+1];
      
                // Max gold collected from taking
                // either of the above 3 paths
                goldTable[row][col] = gold[row][col]
                 + Math.max(right, Math.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 = Math.max(res, goldTable[i][0]);

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

# Python program to solve


# Gold Mine problem
  
MAX = 100
  
# Returns maximum amount of
# gold that can be collected
# when journey started from
# first column and moves
# allowed are right, right-up
# and right-down
def getMaxGold(gold, m, n):
  
    # Create a table for storing
    # intermediate results
    # and initialize all cells to 0.
    # The first row of
    # goldMineTable gives the
    # maximum gold that the miner
    # can collect when starts that row
    goldTable = [[0 for i in range(n)]
                        for j in range(m)]
  
    for col in range(n-1, -1, -1):
        for row in range(m):
  

864
Chapter 120. Gold Mine Problem

            # Gold collected on going to


            # the cell on the rigth(->)
            if (col == n-1):
                right = 0
            else:
                right = goldTable[row][col+1]
  
            # Gold collected on going to
            # the cell to right up (/)
            if (row == 0 or col == n-1):
                right_up = 0
            else:
                right_up = goldTable[row-1][col+1]
  
            # Gold collected on going to
            # the cell to right down (\)
            if (row == m-1 or col == n-1):
                right_down = 0
            else:
                right_down = goldTable[row+1][col+1]
  
            # Max gold collected from taking
            # either of the above 3 paths
            goldTable[row][col] = gold[row][col] + max(right, right_up, right_down)
                                                             
    # The max amount of gold
    # collected will be the max
    # value in first column of all rows
    res = goldTable[0][0]
    for i in range(1, m):
        res = max(res, goldTable[i][0])
  
    return res
      
# Driver code
gold = [[1, 3, 1, 5],
    [2, 2, 4, 1],
    [5, 0, 2, 3],
    [0, 6, 1, 2]]
  
m = 4
n = 4
  
print(getMaxGold(gold, m, n))
  
# This code is contributed
# by Soumen Ghosh.              

865
Chapter 120. Gold Mine Problem

Output:

16

Time Complexity :O(m*n)


Space Complexity :O(m*n)

Source

https://www.geeksforgeeks.org/gold-mine-problem/

866
Chapter 121

Hilbert Matrix

Hilbert Matrix - GeeksforGeeks


A Hilbert Matrix is a square matrix whose each element is a unit fraction.
Properties:

1. It is a symmetric matrix.
2. Its determinant value is always positive.

Source

https://www.geeksforgeeks.org/hilbert-matrix/

867
Chapter 122

In-place convert matrix in


specific order

In-place convert matrix in specific order - GeeksforGeeks


Write a code to convert a matrix in specific way without using extra space.

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.

// Program for convert matrix in specific order

868
Chapter 122. In-place convert matrix in specific order

// using in-place matrix transpose


#include <bits/stdc++.h>
#define HASH_SIZE 128
using namespace std;
  
// Non-square matrix transpose of matrix of size r x c
// and base address A
void transformMatrix(int *A, int r, int c)
{
    // Invert even rows
    for (int i = 1; i < r; i = i + 2)
        for (int j1 = 0, j2 = c - 1; j1 < j2; j1++, j2--)
            swap(*(A + i*c + j1), *(A + i*c + j2));
  
    // Rest of the code is from below post
    // http://tinyurl.com/j79j445
    int size = r*c - 1;
    int 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
  
    bitset<HASH_SIZE> b; // hash to mark moved elements
  
    b.reset();
    b[0] = b[size] = 1;
    int 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 1
            // 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++)
            ;
    }

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

Inplace (Fixed space) M x N


size matrix transpose | Updated

Inplace (Fixed space) M x N size matrix transpose | Updated - GeeksforGeeks


About four months of gap (missing GFG), a new post. Given an M x N matrix, transpose
the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array.
If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D
array across it’s diagonal (try yourself). How to transpose an arbitrary size matrix inplace?
See the following matrix,

a b c a d g j
d e f ==> b e h k
g h i c f i l
j k l

As per 2D numbering in C/C++, corresponding location mapping looks like,

Org element New


0 a 0
1 b 4
2 c 8
3 d 1
4 e 5
5 f 9
6 g 2
7 h 6
8 i 10
9 j 3
10 k 7
11 l 11

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.

• 1->4->5->9->3->1 – Total 5 elements form the cycle


• 2->8->10->7->6->2 – Another 5 elements form the cycle
• 0 – Self cycle
• 11 – Self cycle

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,

ol = or x C + oc (ignore base reference for simplicity)

It is to be moved to new location nl in the transposed matrix, say nl = A[nr][nc], or in


C/C++ terms

nl = nr x R + nc (R - column count, C is row count as the matrix is transposed)

Observe, nr = oc and nc = or, so replacing these for nl,

nl = oc x R + or -----> [eq 1]

after solving for relation between ol and nl, we get

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,

nl mod (N-1) = (ol x R - or x (N-1)) mod (N-1)


= (ol x R) mod (N-1) - or x (N-1) mod(N-1)
= ol x R mod (N-1), since second term evaluates to zero
nl = (ol x R) mod (N-1), since nl is always less than N-1

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,

// Program for in-place matrix transpose


#include <stdio.h>
#include <iostream>
#include <bitset>
#define HASH_SIZE 128
  
using namespace std;
  
// 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\n");
}
  
// Non-square matrix transpose of matrix of size r x c and base address A
void MatrixInplaceTranspose(int *A, int r, int c)
{
    int size = r*c - 1;
    int 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

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

Inplace rotate square matrix by


90 degrees | Set 1

Inplace rotate square matrix by 90 degrees | Set 1 - GeeksforGeeks


Given an 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

An approach that requires extra space is already discussed here.

879
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1

How to do without extra space?


Below are some important observations.
First row of source –> First column of destination, elements filled in opposite order
Second row of source –> Second column of destination, elements filled in opposite order
so … on
Last row of source –> Last column of destination, elements filled in opposite order.
An N x N matrix will have floor(N/2) square cycles. For example, a 4 X 4 matrix will have
2 cycles. The first cycle is formed by its 1st row, last column, last row and 1st column. The
second cycle is formed by 2nd row, second-last column, second-last row and 2nd column.
The idea is for each square cycle, we swap the elements involved with the corresponding
cell in the matrix in anti-clockwise direction i.e. from top to left, left to bottom, bottom
to right and from right to top one at a time. We use nothing but a temporary variable to
achieve this.
Below steps demonstrate the idea

First Cycle (Involves Red Elements)


1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Moving first group of four elements (First


elements of 1st row, last row, 1st column
and last column) of first cycle in counter
clockwise.
4 2 3 16
5 6 7 8
9 10 11 12
1 14 15 13

Moving next group of four elements of


first cycle in counter clockwise
4 8 3 16
5 6 7 15
2 10 11 12
1 14 9 13

Moving final group of four elements of


first cycle in counter clockwise
4 8 12 16
3 6 7 15
2 10 11 14

880
Chapter 124. Inplace rotate square matrix by 90 degrees | Set 1

1 5 9 13

Second Cycle (Involves Blue Elements)


4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13

Fixing second cycle


4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Below is the implementation of above idea.


C++

// C++ program to rotate a matrix by 90 degrees


#include <bits/stdc++.h>
#define N 4
using namespace std;
  
void displayMatrix(int mat[N][N]);
  
// An Inplace function to rotate a N x N matrix
// by 90 degrees in anti-clockwise direction
void rotateMatrix(int mat[][N])
{
    // Consider all squares one by one
    for (int x = 0; x < N / 2; x++)
    {
        // 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];

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

// Java program to rotate a matrix by 90 degrees


import java.io.*;
   
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++)
        {
            // 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[][])

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

# Python3 program to rotate a matrix by 90 degrees


N = 4
  
# An Inplace function to rotate 
# N x N matrix by 90 degrees in
# anti-clockwise direction
def rotateMatrix(mat):
      
    # Consider all squares one by one
    for x in range(0, int(N/2)):
          
        # Consider elements in group   
        # of 4 in current square
        for y in range(x, N-x-1):
              
            # 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 pr the matrix
def displayMatrix( mat ):
      
    for i in range(0, N):
          
        for j in range(0, N):
              
            print (mat[i][j], end = ' ')
        print ("")
      
      
  

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

        // 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);
    }
}
  
// This code is contributed by ajit

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

Interchange elements of first


and last rows in matrix

Interchange elements of first and last rows in matrix - GeeksforGeeks


Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show
the resulting matrix.
Examples :

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++

// C++ code to swap the element of first


// and last row and display the result
#include <iostream>
using namespace std;
  
#define n 4
  
void interchangeFirstLast(int m[][n])
{
        int rows = n;
          
        // swapping of element between first
        // and last rows
        for (int i = 0; i < n; i++)
        {
            int t = m[0][i];
            m[0][i] = m[rows - 1][i];
            m[rows - 1][i] = t;
        }

  
// Driver function
int main()
{
    // input in the array
    int m[n][n] = { { 8, 9, 7, 6 },
                { 4, 7, 6, 5 },
                { 3, 2, 1, 8 },
                { 9, 9, 7, 7 } }; 
                  
    interchangeFirstLast(m); 
      
    // printing the interchanged matrix
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++) 
            cout << m[i][j] << " ";
        cout << endl;
    }
}
  
// This code is contributed by Anant Agarwal.

Java

// Java code to swap the element of first

893
Chapter 125. Interchange elements of first and last rows in matrix

// and last row and display the result


import java.io.*;
  
public class Interchange {
      
    static void interchangeFirstLast(int m[][])
    {
        int rows = m.length;
          
        // swapping of element between first
        // and last rows
        for (int i = 0; i < m[0].length; i++) {
            int t = m[0][i];
            m[0][i] = m[rows-1][i];
            m[rows-1][i] = t;
        }
    }
      
    // Driver code
    public static void main(String args[]) throws IOException
    {
        // input in the array
        int m[][] = { { 8, 9, 7, 6 },
                    { 4, 7, 6, 5 },
                    { 3, 2, 1, 8 },
                    { 9, 9, 7, 7 } }; 
                      
        interchangeFirstLast(m); 
          
        // printing the interchanged matrix
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) 
                System.out.print(m[i][j] + " ");
            System.out.println();
        }
    }
}

Python3

# Python code to swap the element


# of first and last row and display
# the result
  
def interchangeFirstLast(mat, n, m):
    rows = n
      
    # swapping of element between

894
Chapter 125. Interchange elements of first and last rows in matrix

    # first and last rows


    for i in range(n):
        t = mat[0][i]
        mat[0][i] = mat[rows-1][i]
        mat[rows-1][i] = t
  
# Driver Program
mat = [[8, 9, 7, 6],
          [4, 7, 6, 5],
       [3, 2, 1, 8],
       [9, 9, 7, 7]]
  
n = 4
m = 4
interchangeFirstLast(mat, n, m)
  
# printing the interchanged matrix
for i in range(n):
    for j in range(m):
        print(mat[i][j], end = " ")
    print("\n")
  
# This code is contributed by Shrikant13.

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

Kronecker Product of two


matrices

Kronecker Product of two matrices - GeeksforGeeks

Given a matrix A and a matrix B, their Kronecker product C =

A tensor B, also called their matrix direct product, is an matrix.

A tensor B = |a11B a12B|


|a21B a22B|

= |a11b11 a11b12 a12b11 a12b12|


|a11b21 a11b22 a12b21 a12b22|
|a11b31 a11b32 a12b31 a12b32|
|a21b11 a21b12 a22b11 a22b12|
|a21b21 a21b22 a22b21 a22b22|
|a21b31 a21b32 a22b31 a22b32|

Examples :

1. The matrix direct(kronecker) product of the 2×2 matrix A


and the 2×2 matrix B is given by the 4×4 matrix :

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

2. The matrix direct(kronecker) product of the 2×3 matrix A


and the 3×2 matrix B is given by the 6×6 matrix :

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 :

// C code to find the Kronecker Product of two


// matrices and stores it as matrix C
#include <stdio.h>
  
// rowa and cola are no of rows and columns
// of matrix A
// rowb and colb are no of rows and columns
// of matrix B
const int cola = 2, rowa = 3, colb = 3, rowb = 2;
  
// Function to computes the Kronecker Product
// of two matrices
void Kroneckerproduct(int A[][cola], int B[][colb])
{
  
    int C[rowa * rowb][cola * colb];
  
    // i loops till rowa
    for (int i = 0; i < rowa; i++) {
  
        // 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++) {

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

// Java code to find the Kronecker Product of


// two matrices and stores it as matrix C
import java.io.*;
import java.util.*;
  
class GFG {
          
    // rowa and cola are no of rows and columns
    // of matrix A
    // rowb and colb are no of rows and columns
    // of matrix B
    static int cola = 2, rowa = 3, colb = 3, rowb = 2;
      
    // Function to computes the Kronecker Product
    // of two matrices
    static void Kroneckerproduct(int A[][], int B[][])
    {
      
        int[][] C= new int[rowa * rowb][cola * colb];
      
        // i loops till rowa
        for (int i = 0; i < rowa; i++) 
        {

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

# Python3 code to find the Kronecker Product of two


# matrices and stores it as matrix C
   
# rowa and cola are no of rows and columns
# of matrix A

899
Chapter 126. Kronecker Product of two matrices

# rowb and colb are no of rows and columns


# of matrix B
cola = 2
rowa = 3
colb = 3
rowb = 2
   
# Function to computes the Kronecker Product
# of two matrices
  
def Kroneckerproduct( A , B ):
      
    C = [[0 for j in range(cola * colb)] for i in range(rowa * rowb)]
   
    # i loops till rowa
    for i in range(0, rowa):
          
        # k loops till rowb
        for k in range(0, rowb):
   
            # j loops till cola
            for j in range(0, cola):
   
                # l loops till colb
                for l in range(0, colb):
   
                    # 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]
                    print (C[i + l + 1][j + k + 1],end=' ')
              
              
            print ("\n")
          
  
# Driver code.
  
A = [[0 for j in range(2)] for i in range(3)]
B = [[0 for j in range(3)] for i in range(2)]
  
A[0][0] = 1
A[0][1] = 2
A[1][0] = 3
A[1][1] = 4
A[2][0] = 1
A[2][1] = 0
  

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#

// C# code to find the Kronecker Product of


// two matrices and stores it as matrix C
using System;
  
class GFG {
          
    // rowa and cola are no of rows 
    // and columns of matrix A
    // rowb and colb are no of rows
    //  and columns of matrix B
    static int cola = 2, rowa = 3;
    static int colb = 3, rowb = 2;
      
    // Function to computes the Kronecker 
    // Product of two matrices
    static void Kroneckerproduct(int [,]A, int [,]B)
    {
      
        int [,]C= new int[rowa * rowb, 
                          cola * colb];
      
        // i loops till rowa
        for (int i = 0; i < rowa; i++) 
        {
      
            // 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++)

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

// Kronecker Product of two matrices


function Kroneckerproduct($A, $B)
{
    global $cola;
    global $rowa;
    global $colb;
    global $rowb;
  
  
    //$C[$rowa * $rowb][$cola * $colb];
    $C;
  
    // i loops till rowa
    for ( $i = 0; $i < $rowa; $i++)
    {
  
        // k loops till rowb
        for ($k = 0; $k < $rowb; $k++) 
        {
  
            // j loops till cola
            for ( $j = 0; $j < $cola; $j++)  
            {
  
                // l loops till colb
                for ($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];
                    echo ($C[$i + $l + 1][$j + $k + 1]), "\t" ;
                }
            }
        echo "\n";
        }
    }
}
  
// Driver Code
$A = array (array (1, 2), 
            array (3, 4), 
            array (1, 0));
$B = array (array (0, 5, 2),
            array (6, 7, 3));
  

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

Improved By : nitin mittal, jit_t

Source

https://www.geeksforgeeks.org/kronecker-product-two-matrices/

904
Chapter 127

Kruskal’s Algorithm (Simple


Implementation for Adjacency
Matrix)

Kruskal’s Algorithm (Simple Implementation for Adjacency Matrix) - GeeksforGeeks


Below are the steps for finding MST using Kruskal’s algorithm

1. Sort all the edges in non-decreasing order of their weight.


2. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

We have discussed one implementation of Kruskal’s algorithm in previous post. In this post,
a simpler implementation for adjacency matrix is discussed.

// Simple C++ implementation for Kruskal's


// algorithm
#include <bits/stdc++.h>
using namespace std;
  
#define V 5
int parent[V];
  
// Find set of vertex i
int find(int i)
{
    while (parent[i] != i)
        i = parent[i];
    return i;

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:

Edge 0:(0, 1) cost:2


Edge 1:(1, 2) cost:3
Edge 2:(1, 4) cost:5
Edge 3:(0, 3) cost:6

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

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.

10, 20, 30, 40


15, 25, 35, 45
24, 29, 37, 48
32, 33, 39, 50
The 3rd smallest element is 20 and 7th smallest element is 30

The idea is to use min heap. Following are detailed step.


1) Build a min heap of elements from first row. A heap entry also stores row number and
column number.
2) Do following k times.
…a) Get minimum element (or root) from min heap.
…b) Find row number and column number of the minimum element.
…c) Replace root with the next element from same column and min-heapify the root.
3) Return the last extracted root.
Following is C++ implementation of above algorithm.

// kth largest element in a 2d array sorted row-wise and column-wise


#include<iostream>

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

int kthSmallest(int mat[4][4], int n, int k)


{
    // k must be greater than 0 and smaller than n*n
    if (k <= 0 || k > n*n)
       return INT_MAX;
  
    // Create a min heap of elements from first row of 2D array
    HeapNode harr[n];
    for (int i = 0; i < n; i++)
        harr[i] =  {mat[0][i], 0, i};
    buildHeap(harr, n);
  
    HeapNode hr;
    for (int i = 0; i < k; i++)
    {
       // Get current heap root
       hr = harr[0];
  
       // Get next value from column of root's value. If the
       // value stored at root was last value in its column,
       // then assign INFINITE as next value
       int nextval = (hr.r < (n-1))? mat[hr.r + 1][hr.c]: INT_MAX;
  
       // Update heap root with next value
       harr[0] =  {nextval, (hr.r) + 1, hr.c};
  
       // Heapify root
       minHeapify(harr, 0, n);
    }
  
    // Return the value at last extracted root
    return hr.val;
}
  
// driver program to test above function
int main()
{
  int mat[4][4] = { {10, 20, 30, 40},
                    {15, 25, 35, 45},
                    {25, 29, 37, 48},
                    {32, 33, 39, 50},
                  };
  cout << "7th smallest element is " << kthSmallest(mat, 4, 7);
  return 0;
}

Output:

910
Chapter 128. Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1

7th smallest element is 30

Time Complexity: The above solution involves following steps.


1) Build a min heap which takes O(n) time
2) Heapify k times which takes O(kLogn) time.
Therefore, overall time complexity is O(n + kLogn) time.
The above code can be optimized to build a heap of size k when k is smaller than n. In that
case, the kth smallest element must be in first k rows and k columns.
We will soon be publishing more efficient algorithms for finding the kth smallest element.
This article is compiled by Ravi 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/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

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:

Input : mat[][] = { {0, 0, 1, 1},


{0, 1, 1, 0},
{1, 1, 1, 0},
{1, 0, 0, 1} }
Output : 8 sq. units
(Top, left): (0, 0)
(Bottom, right): (3, 1)

Input : mat[][] = { {0, 0, 1, 1},


{0, 1, 1, 1} }
Output : 6 sq. units

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.

// C++ implementation to find largest area rectangular


// submatrix with equal number of 1's and 0's
#include <bits/stdc++.h>
  
using namespace std;
  
#define MAX_ROW 10
#define MAX_COL 10
  
// This function basically finds largest 0
// sum subarray in arr[0..n-1]. If 0 sum
// does't exist, then it returns false. Else
// it returns true and sets starting and
// ending indexes as start and end.
bool subArrWithSumZero(int arr[], int &start, 
                              int &end, int n)
{
    // to store cumulative sum
    int sum[n];
      
    // Initialize all elements of sum[] to 0
    memset(sum, 0, sizeof(sum));
      
    // map to store the indexes of sum
    unordered_map<int, int> um;
      
    // build up the cumulative sum[] array
    sum[0] = arr[0];
    for (int i=1; i<n; i++)
        sum[i] = sum[i-1] + arr[i];
      
    // to store the maximum length subarray
    // with sum equal to 0
    int maxLen = 0;
      
    // traverse to the sum[] array
    for (int i=0; i<n; i++)    
    {

913
Chapter 129. Largest area rectangular sub-matrix with equal number of 1’s and 0’s

        // if true, then there is a subarray


        // with sum equal to 0 from the
        // beginning up to index 'i'
        if (sum[i] == 0)
        {
            // update the required variables
            start = 0; 
            end = i;
            maxLen = (i+1);
        }
          
        // else if true, then sum[i] has not 
        // seen before in 'um'
        else if (um.find(sum[i]) == um.end())
            um[sum[i]] = i;
          
        // sum[i] has been seen before in the
        // unordered_map 'um'    
        else
        {
            // if previous subarray length is smaller
            // than the current subarray length, then
            // update the required variables
            if (maxLen < (i-um[sum[i]]))
            {
                maxLen = (i-um[sum[i]]);
                start = um[sum[i]] + 1;
                end = i;
            }
        }    
    }    
      
    // if true, then there is no
    // subarray with sum equal to 0
    if (maxLen == 0)
        return false;
          
    // else return true    
    return true;    
}
  
// function to find largest area rectangular
// submatrix with equal number of 1's and 0's
void maxAreaRectWithSumZero(int mat[MAX_ROW][MAX_COL], 
                                    int row, int col)
{
    // to store intermediate values
    int temp[row], startRow, endRow;

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

    // with equal number of 1's and 0's


    if (maxArea == 0)
        cout << "No such rectangular submatrix exists:";
      
    // displaying the top left and bottom right boundaries
    // with the area of the rectangular submatrix    
    else
    {
        cout << "(Top, Left): " 
             << "(" << finalTop << ", " << finalLeft
             << ")" << endl; 
               
        cout << "(Bottom, Right): " 
             << "(" << finalBottom << ", " << finalRight 
             << ")" << endl;      
          
        cout << "Area: " << maxArea << " sq.units";     
    }
}
  
// Driver program to test above
int main()
{
    int mat[MAX_ROW][MAX_COL] = { {0, 0, 1, 1},
                                    {0, 1, 1, 0},
                                    {1, 1, 1, 0},
                                  {1, 0, 0, 1} };    
    int row = 4, col = 4;
    maxAreaRectWithSumZero(mat, row, col);
    return 0;                      
                        

Output:

(Top, Left): (0, 0)


(Bottom, Right): (3, 1)
Area: 8 sq.units

Time Complexity: O(n3 )


Auxiliary Space: O(n)

Source

https://www.geeksforgeeks.org/largest-area-rectangular-sub-matrix-equal-number-1s-0s/

916
Chapter 130

Largest connected component


on a grid

Largest connected component on a grid - GeeksforGeeks


Given a grid with different colors in a different cell, each color represented by a different
number. The task is to find out the largest connected component on the grid. Largest
component grid refers to a maximum set of cells such that you can move from any cell to
any other cell in this set by only moving between side-adjacent cells from the set.
Examples:

Input :

917
Chapter 130. Largest connected component on a grid

Grid of different colors


Output : 9

Largest connected component of 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

Graph representation of grid


.
At every cell (i, j), a BFS can be done. The possible moves from a cell will be either to
right, left, top or bottom. Move to only those cells which are in range and are of the
same color. It the same nodes have been visited previously, then the largest component
value of the grid is stored in result[][] array. Using memoization, reduce the number of
BFS on any cell. visited[][] array is used to mark if the cell has been visited previously
and count stores the count of the connected component when a BFS is done for every cell.
Store the maximum of the count and print the resultant grid using result[][] array.
Below is the illustration of the above approach:

C++

// CPP program to print the largest


// connected component in a grid
#include <bits/stdc++.h>
using namespace std;
  
const int n = 6;
const int m = 8;

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

    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);
            }
            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);
}
// Drivers Code
int main()
{
    int input[n][m] = { { 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);
    return 0;
}

Java

922
Chapter 130. Largest connected component on a grid

// Java program to print the largest


// connected component in a grid
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{
static final int n = 6;
static final int m = 8;
  
// stores information about which cell
// are already visited in a particular BFS
static final int visited[][] = new int [n][m];
  
// result stores the final result grid
static final int result[][] = new int [n][m];
  
// stores the count of
// cells in the largest 
// connected component
static int COUNT;
  
// Function checks if a cell 
// is valid i.e it is inside 
// the grid and equal to the key
static boolean is_valid(int x, int y, 
                        int key, 
                        int input[][])
{
    if (x < n && y < m &&
        x >= 0 && y >= 0) 
    {
        if (visited[x][y] == 0 && 
            input[x][y] == key)
            return true;
        else
            return false;
    }
    else
        return false;
}
  
// BFS to find all cells in
// connection with key = input[i][j]
static void BFS(int x, int y, int i,
                int j, int input[][])
{

923
Chapter 130. Largest connected component on a grid

    // 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)) == true)
            BFS(x, y, i + y_move[u],
                      j + x_move[u], input);
}
  
// called every time before 
// a BFS so that visited 
// array is reset to zero
static 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.
static void reset_result(int key,
                         int input[][])
{
    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < m; j++) 
        {
            if (visited[i][j] ==1 && 
                input[i][j] == key)
                result[i][j] = visited[i][j];
            else
                result[i][j] = 0;

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:

The largest connected component of the grid is :9


. . . . . . . .
. 1 1 . . . . .
. . 1 1 . . . .
. . . 1 . . . .
. . . 1 1 . . .
. . . 1 1 . . .

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

Largest rectangular sub-matrix


having sum divisible by k

Largest rectangular sub-matrix having sum divisible by k - GeeksforGeeks


Given a n x n matrix of integers. The problem is to find the largest area rectangular
sub-matrix having sum divisible by the given value k.
Examples:

Input : mat[][] = { {1, 2, -1, -4},


{-8, -3, 4, 2},
{3, 8, 10, 1},
{-4, -1, 1, 7} }

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.

// C++ implementation to find largest rectangular


// sub-matrix having sum divisible by k
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 10
  
// function to find the longest subarray with sum divisible
// by k. The function stores starting and ending indexes of
// the subarray at addresses pointed by start and finish
// pointers respectively.
void longSubarrWthSumDivByK(int arr[], int n, int k,
                            int& start, int& finish)
{
    // unodered map 'um' implemented as
    // hash table
    unordered_map<int, int> um;
  
    // 'mod_arr[i]' stores (sum[0..i] % k)
    int mod_arr[n];
    int curr_sum = 0, max = 0;
  
    // traverse arr[] and build up the
    // array 'mod_arr[]'
    for (int i = 0; i < n; i++) {
        curr_sum += arr[i];
  
        // as the sum can be negative, taking modulo twice
        mod_arr[i] = ((curr_sum % k) + k) % k;
    }
  
    for (int i = 0; i < n; i++) {
  
        // if true then sum(0..i) is divisible
        // by k
        if (mod_arr[i] == 0) {
  

929
Chapter 131. Largest rectangular sub-matrix having sum divisible by k

            // update variables


            max = i + 1;
            start = 0;
            finish = i;
        }
  
        // if value 'mod_arr[i]' not present in 'um'
        // then store it in 'um' with index of its
        // first occurrence
        else if (um.find(mod_arr[i]) == um.end())
            um[mod_arr[i]] = i;
  
        else
            // if true, then update variables
            if (max < (i - um[mod_arr[i]])) {
            max = i - um[mod_arr[i]];
            start = um[mod_arr[i]] + 1;
            finish = i;
        }
    }
}
  
// function to find largest rectangular sub-matrix
// having sum divisible by k
void findLargestSubmatrix(int mat[SIZE][SIZE], int n, int k)
{
    // Variables to store the final output
    int finalLeft, finalRight, finalTop, finalBottom;
  
    int left, right, i, maxArea = 0;
    int temp[n], start, finish;
  
    // 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];
  
            // The longSubarrWthSumDivByK() function sets

930
Chapter 131. Largest rectangular sub-matrix having sum divisible by k

            // the values of 'start' and 'finish'. So 


            // submatrix having sum divisible by 'k' between 
            // (start, left) and (finish, right) which is
            // the largest submatrix with boundary columns 
            // strictly as left and right.
            longSubarrWthSumDivByK(temp, n, k, start, finish);
  
            // Calculate current area and compare it with 
            // maximum area so far. If maxArea is less, then 
            // update maxArea and other output values
            if (maxArea < ((right - left + 1) * 
                          (finish - start + 1))) {
                finalLeft = left;
                finalRight = right;
                finalTop = start;
                finalBottom = finish;
                maxArea = (right - left + 1) * (finish - start + 1);
            }
        }
    }
  
    // Print final values
    cout << "(Top, Left): (" << finalTop << ", "
         << finalLeft << ")\n";
    cout << "(Bottom, Right): (" << finalBottom << ", "
         << finalRight << ")\n";
    cout << "Area: " << maxArea;
}
  
// Driver program to test above functions
int main()
{
    int mat[SIZE][SIZE] = { { 1, 2, -1, -4 },
                            { -8, -3, 4, 2 },
                            { 3, 8, 10, 1 },
                            { -4, -1, 1, 7 } };
  
    int n = 4, k = 5;
    findLargestSubmatrix(mat, n, k);
  
    return 0;
}

Output:

(Top, Left): (0, 0)


(Bottom, Right): (2, 3)

931
Chapter 131. Largest rectangular sub-matrix having sum divisible by k

Area: 12

Time Complexity: O(n^3).


Auxiliary Space: O(n).

Source

https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-sum-divisible-k/

932
Chapter 132

Largest rectangular sub-matrix


whose sum is 0

Largest rectangular sub-matrix whose sum is 0 - GeeksforGeeks


Given a 2D matrix, find the largest rectangular sub-matrix whose sum is 0. for example
consider the following N x M input matrix

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.

// A C++ program to find Largest rectangular


// sub-matrix whose sum is 0
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// This function basically finds largest 0
// sum aubarray in temp[0..n-1]. If 0 sum
// does't exist, then it returns false. Else
// it returns true and sets starting and
// ending indexes as starti and endj.
bool sumZero(int temp[], int* starti,
            int* endj, int n)
{
    // Map to store the previous sums
    map<int, int> presum;
    int sum = 0; // Initialize sum of elements
  
    // Initialize length of sub-array with sum 0
    int max_length = 0;
  
    // Traverse through the given array
    for (int i = 0; i < n; i++)

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

    // Return true if max_length is non-zero


    return (max_length != 0);
}
  
// The main function that finds Largest rectangle
// sub-matrix in a[][] whose sum is 0.
void sumZeroMatrix(int a[][MAX], int row, int col)
{
    int temp[row];
  
    // Variables to store the final output
    int fup = 0, fdown = 0, fleft = 0, fright = 0;
    int sum;
    int up, down;
    int maxl = 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 for every row 'i'
            for (int i = 0; i < row; i++)
                temp[i] += a[i][right];
  
            // Find largest subarray with 0 sum in
            // temp[]. The sumZero() function also
            // sets values of start and finish. So
            // 'sum' is sum of rectangle between (start,
            // left) and (finish, right) which is
            // boundary columns strictly as left and right.
            bool sum = sumZero(temp, &up, &down, row);
            int ele = (down - up + 1) * (right - left + 1);
  
            // Compare no. of elements with previous
            // no. of elements in sub-Matrix.
            // If new sub-matrix has more elements
            // then update maxl and final boundaries
            // like fup, fdown, fleft, fright
            if (sum && ele > maxl)
            {
                fup = up;

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

Largest sum Zigzag sequence in


a matrix

Largest sum Zigzag sequence in a matrix - GeeksforGeeks


Given a matrix of size n x n, find sum of the Zigzag sequence with the largest sum. A zigzag
sequence starts from the top and ends at the bottom. Two consecutive elements of sequence
cannot belong to same column.
Examples:

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

This problem has Optimal Substructure.

Maximum Zigzag sum starting from arr[i][j] to a


bottom cell can be written as :
zzs(i, j) = arr[i][j] + max(zzs(i+1, k)),
where k = 0, 1, 2 and k != j
zzs(i, j) = arr[i][j], if i = n-1

938
Chapter 133. Largest sum Zigzag sequence in a matrix

We have to find the largest among all as


Result = zzs(0, j) where 0 <= j < n

C++

// C++ program to find the largest sum zigzag sequence


#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Returns largest sum of a Zigzag sequence starting
// from (i, j) and ending at a bottom cell.
int largestZigZagSumRec(int mat[][MAX], int i,
                                int j, int n)
{
   // If we have reached bottom
   if (i == n-1)
     return 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 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)
{
   // 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},

939
Chapter 133. Largest sum Zigzag sequence in a matrix

                        {11, 3, 15}};
    cout << "Largest zigzag sum: " << largestZigZag(mat, n);
    return 0;
}

Java

// Java program to find the largest sum 


// zigzag sequence
import java.io.*;
  
class GFG {
  
    static int MAX = 100;
      
    // Returns largest sum of a Zigzag 
    // sequence starting from (i, j) 
    // and ending at a bottom cell.
    static int largestZigZagSumRec(int mat[][],
                            int i, int j, int n)
    {
          
        // If we have reached bottom
        if (i == n-1)
            return 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 = Math.max(zzs, 
               largestZigZagSumRec(mat, i+1, k, n));
          
        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, 

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#

// C# program to find the largest sum 


// zigzag sequence
using System;
class GFG {
  
    // static int MAX = 100;
      
    // Returns largest sum of a Zigzag 
    // sequence starting from (i, j) 
    // and ending at a bottom cell.
    static int largestZigZagSumRec(int [,]mat,
                          int i, int j, int n)
    {
          
        // If we have reached bottom
        if (i == n-1)
            return 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 = Math.Max(zzs, largestZigZagSumRec(mat, 
                                           i + 1, k, n));

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

function largestZigZagSumRec($mat, $i,


                              $j, $n)
{
    // If we have reached bottom
    if ($i == $n - 1)
        return $mat[$i][$j];
      
    // Find the largest sum
    // by considering all
    // possible next elements
    // in sequence.
    $zzs = 0;
    for ($k = 0; $k < $n; $k++)
        if ($k != $j)
        $zzs = max($zzs, largestZigZagSumRec($mat, 
                                $i + 1, $k, $n));
      
    return $zzs + $mat[$i][$j];
}
  
// Returns largest possible
// sum of a Zizag sequence
// starting from top and 
// ending at bottom.
function largestZigZag( $mat, $n)
{
      
    // Consider all cells of top
    // row as starting point
    $res = 0;
    for ($j = 0; $j < $n; $j++)
        $res = max($res, largestZigZagSumRec(
                            $mat, 0, $j, $n));
      
    return $res;
}
  
    // Driver Code
    $n = 3;
    $mat = array(array(4, 2, 1),
                 array(3, 9, 6),
                 array(11, 3, 15));
    echo "Largest zigzag sum: " , largestZigZag($mat, $n);
      
// This code is contributed by anuj_67.
?>

Output:

943
Chapter 133. Largest sum Zigzag sequence in a matrix

Largest zigzag sum: 28

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.

Recursion tree for cell (0, 0)


zzs(0,0)
/ \
zzs(1,1) zzs(1,2)
/ \ / \
zzs(2,0) zzs(2,2) zzs(2,0) zzs(2,1)

Recursion tree for cell (0, 1)


zzs(0,1)
/ \
zzs(1,0) zzs(1,2)
/ \ / \
zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,1)

Recursion tree for cell (0, 2)


zzs(0,2)
/ \
zzs(1,0) zzs(1,1)
/ \ / \
zzs(2,1) zzs(2,2) zzs(2,0) zzs(2,2)

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.

// Memoization based C++ program to find the largest


// sum zigzag sequence
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
int dp[MAX][MAX];
  
// Returns largest sum of a Zigzag sequence starting
// from (i, j) and ending at a bottom cell.
int largestZigZagSumRec(int mat[][MAX], int i,

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

References: Asked in Directi


Improved By : vt_m

Source

https://www.geeksforgeeks.org/largest-sum-zig-zag-sequence-in-a-matrix/

946
Chapter 134

Latin Square

Latin Square - GeeksforGeeks


A Latin Square is a n x n grid filled by n distinct numbers each appearing exactly once
in each row and column. Given an input n, we have to print a n x n matrix consisting of
numbers from 1 to n each appearing exactly once in each row and each column.
Examples :

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?

• In the first row, the numbers are stored from 1 to n serially.


• the second row, the numbers are shifted to the right by one column. i.e, 1 is stored at
2nd column now and so on.
• In the third row, the numbers are shifted to the right by two columns. i.e, 1 is stored
at 3rd column now and so on.
• We continue same way for remaining rows.

Note: There may be more than one possible configuration of a n x n latin square.
C++

947
Chapter 134. Latin Square

// C++ program to pritn Latin Square


#include<stdio.h>
  
// Function to print n x n Latin Square
void printLatin(int n)
{
    // A variable to control the rotation
    // point.
    int k = n+1;
  
    // Loop to print rows
    for (int i=1; i<=n; i++)
    {
        // This loops runs only after first
        // iteration of outer loop. It prints
        // numbers from n to k
        int temp = k;
        while (temp <= n)
        {
            printf("%d ", temp);
            temp++;
        }
  
        // This loop prints numbers from 1 to k-1.
        for (int j=1; j<k; j++)
            printf("%d ", j);
  
        k--;
        printf("\n");
    }
}
  
// Driver program to test above function
int main(void)
{
    int n = 5;
  
    // Invoking printLatin function
    printLatin(n);
  
    return 0;
}

Java

// Java program to pritn Latin Square


class GFG {
      

948
Chapter 134. Latin Square

    // Function to print n x n Latin Square


    static void printLatin(int n)
    {
          
        // A variable to control the 
        // rotation point.
        int k = n+1;
      
        // Loop to print rows
        for (int i = 1; i <= n; i++)
        {
  
            // This loops runs only after
            // first iteration of outer 
            // loop. It prints
            // numbers from n to k
            int temp = k;
  
            while (temp <= n)
            {
                System.out.print(temp + " ");
                temp++;
            }
      
            // This loop prints numbers from
            // 1 to k-1.
            for (int j = 1; j < k; j++)
                System.out.print(j + " ");
      
            k--;
            System.out.println();
        }
    } 
          
    // Driver code
    public static void main (String[] args)
    {
        int n = 5;
          
        // Invoking printLatin function
        printLatin(n);
    }
}
  
// This code is contributed by Anant Agarwal.

C#

949
Chapter 134. Latin Square

// C# program to print Latin Square


using System;
  
class GFG {
      
    // Function to print n x n
    // Latin Square
    static void printLatin(int n)
    {
          
        // A variable to control the 
        // rotation point.
        int k = n + 1;
      
        // Loop to print rows
        for (int i = 1; i <= n; i++)
        {
  
            // This loops runs only after
            // first iteration of outer 
            // loop. It prints numbers
            // from n to k
            int temp = k;
  
            while (temp <= n)
            {
                Console.Write(temp + " ");
                temp++;
            }
      
            // This loop prints numbers from
            // 1 to k-1.
            for (int j = 1; j < k; j++)
                Console.Write(j + " ");
      
            k--;
            Console.WriteLine();
        }
    } 
          
    // Driver code
    public static void Main ()
    {
        int n = 5;
          
        // Invoking printLatin function
        printLatin(n);
    }

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

Longest Increasing Path in


Matrix

Longest Increasing Path in Matrix - GeeksforGeeks


Given a matrix of N rows and M columns. From m[i][j], we can move to m[i+1][j], if
m[i+1][j] > m[i][j], or can move to m[i][j+1] if m[i][j+1] > m[i][j]. The task is print longest
path length if we start from (0, 0).
Examples:

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++

// CPP program to find longest increasing


// path in a matrix.
#include <bits/stdc++.h>
#define MAX 10
using namespace std;
  
// Return the length of LIP in 2D matrix
int LIP(int dp[][MAX], int mat[][MAX], int n, int m, int x, int y)
{
  // If value not calculated yet.
  if (dp[x][y] < 0)
  {
    int result = 0;
      
    // If reach bottom left cell, return 1.
    if (x == n-1 && y == m-1)
     return dp[x][y] = 1;
       
    // If reach the corner of the matrix.
    if (x == n-1 || y == m-1)
      result = 1;
      
    // If value greater than below cell.
    if (mat[x][y] < mat[x+1][y])
      result = 1 + LIP(dp, mat, n, m, x+1, y);
        
    // If value greater than left cell.
    if (mat[x][y] < mat[x][y+1])
      result = max(result, 1 + LIP(dp, mat, n, m, x, y+1));
        
    dp[x][y] = result;
  }
  
  return dp[x][y];
}
  
// Wrapper function
int wrapper(int mat[][MAX], int n, int m)
{
  int dp[MAX][MAX];
  memset(dp, -1, sizeof dp);

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

// Java program to find longest increasing


// path in a matrix.
import java.util.*;
  
class GFG {
      
    // Return the length of LIP in 2D matrix
    static int LIP(int dp[][], int mat[][], int n,
                        int m, int x, int y)
    {
      // If value not calculated yet.
      if (dp[x][y] < 0)
      {
        int result = 0;
           
        // If reach bottom left cell, return 1.
        if (x == n-1 && y == m-1)
         return dp[x][y] = 1;
            
        // If reach the corner of the matrix.
         if (x == n-1 || y == m-1)
          result = 1;
           
        // If value greater than below cell.
         if (x + 1 < n && mat[x][y] < mat[x+1][y])
          result = 1 + LIP(dp, mat, n, m, x+1, y);
             

955
Chapter 135. Longest Increasing Path in Matrix

        // If value greater than left cell.


         if (y + 1 < m && mat[x][y] < mat[x][y+1])
          result = Math.max(result, 1 + 
                    LIP(dp, mat, n, m, x, y+1));
             
        dp[x][y] = result;
      }
       
      return dp[x][y];
    }
      
    // Wrapper function
    static int wrapper(int mat[][], int n, int m)
    {
      int dp[][] = new int[10][10];
      for(int i = 0; i < 10; i++)
          Arrays.fill(dp[i],-1);
       
      return LIP(dp, mat, n, m, 0, 0);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int mat[][] = {
                          { 1, 2, 3, 4 },
                          { 2, 2, 3, 4 },
                          { 3, 2, 3, 4 },
                          { 4, 5, 6, 7 },
                                         };
        int n = 4, m = 4;    
        System.out.println(wrapper(mat, n, m));
              
        }
}
  
// This code is contributed by Arnav Kr. Mandal.    

Output:

Time Complexity: O(N*M).

Source
https://www.geeksforgeeks.org/longest-increasing-path-matrix/

956
Chapter 136

Longest Possible Route in a


Matrix with Hurdles

Longest Possible Route in a Matrix with Hurdles - GeeksforGeeks


Given an M x N matrix, with a few hurdles arbitrarily placed, calculate the length of longest
possible route possible from source to destination within the matrix. We are allowed to move
to only adjacent cells which are not hurdles. The route cannot contains any diagonal moves
and a location once visited in a particular path cannot be visited again.
For example, longest path with no hurdles from source to destination is highlighted for below
matrix. The length of the path is 24.

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 –

// C++ program to find Longest Possible Route in a


// matrix with hurdles

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

        Pair p = { false, INT_MAX };


        return p;
    }
}
  
// A wrapper function over findLongestPathUtil()
void findLongestPath(int mat[R][C], int i, int j, int x,
                                                  int y)
{
    // create a boolean matrix to store info about
    // cells already visited in current route
    bool visited[R][C];
  
    // initailize visited to false
    memset(visited, false, sizeof visited);
  
    // find longest route from (i, j) to (x, y) and
    // print its maximum cost
    Pair p = findLongestPathUtil(mat, i, j, x, y, visited);
    if (p.found)
        cout << "Length of longest possible route is "
             << p.value;
  
    // If the destination is not reachable
    else
        cout << "Destination not reachable from given source";
}
  
// Driver code
int main()
{
    // input matrix with hurdles shown with number 0
    int mat[R][C] =
    {
        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 },
        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
    };
  
    // find longest path with source (0, 0) and
    // destination (1, 7)
    findLongestPath(mat, 0, 0, 1, 7);
  
    return 0;
}

Output:

960
Chapter 136. Longest Possible Route in a Matrix with Hurdles

Length of longest possible route is 24

Source

https://www.geeksforgeeks.org/longest-possible-route-in-a-matrix-with-hurdles/

961
Chapter 137

Magic Square

Magic Square - GeeksforGeeks


A magic square of order n is an arrangement of n^2 numbers, usually distinct integers, in
a square, such that the n numbers in all rows, all columns, and both diagonals sum to the
same constant. A magic square contains the integers from 1 to n^2.
The constant sum in every row, column and diagonal is called the magic constant or magic
sum, M. The magic constant of a normal magic square depends only on n and has the
following value:
M = n(n^2+1)/2

For normal magic squares of order n = 3, 4, 5, ...,


the magic constants are: 15, 34, 65, 111, 175, 260, ...

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:

Magic Square of size 3


-----------------------
2 7 6
9 5 1
4 3 8
Sum in each row & each column = 3*(3^2+1)/2 = 15

Magic Square of size 5


----------------------
9 3 22 16 15
2 21 20 14 8
25 19 13 7 1
18 12 6 5 24

962
Chapter 137. Magic Square

11 10 4 23 17
Sum in each row & each column = 5*(5^2+1)/2 = 65

Magic Square of size 7


----------------------
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
Sum in each row & each column = 7*(7^2+1)/2 = 175

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

6. position of number 6=(1-1,1+1)=(0,2)


7. position of number 7 = (0-1, 2+1) = (-1,3) // this is tricky, see condition 3
new position = (0, 3-2) = (0,1)
8. position of number 8=(0-1,1+1)=(-1,2)=(2,2) //wrap around
9. position of number 9=(2-1,2+1)=(1,3)=(1,0) //wrap around

Based on the above approach, following is the working code:

C/C++

// C++ program to generate odd sized magic squares


#include<stdio.h>
#include<string.h>
  
// A function to generate odd sized magic squares
void generateSquare(int n)
{
    int magicSquare[n][n];
  
    // set all slots as 0
    memset(magicSquare, 0, sizeof(magicSquare));
  
    // Initialize position for 1
    int i = n/2;
    int j = n-1;
  
    // 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;
        }
        if (magicSquare[i][j]) //2nd condition

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

// Java program to generate odd sized magic squares


import java.io.*;
  
class GFG 
{
    // Function to generate odd sized magic squares
    static void generateSquare(int n)
    {
        int[][] magicSquare = new int[n][n];
          
        // Initialize position for 1
        int i = n/2;
        int j = n-1;
   
        // One by one put all values in magic square
        for (int num=1; num <= n*n; )

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

        // Works only when n is odd


        int n = 7;
        generateSquare(n);
    }
}
  
// Contributed by Pramod Kumar

Python

# Python program to generate 


# odd sized magic squares
# A function to generate odd
# sized magic squares
  
def generateSquare(n):
  
    # 2-D array with all 
    # slots set to 0
    magicSquare = [[0 for x in range(n)]
                      for y in range(n)]
  
    # initialize position of 1
    i = n / 2
    j = n - 1
      
    # Fill the magic square
    # by placing values
    num = 1
    while num <= (n * n):
        if i == -1 and j == n: # 3rd condition
            j = n - 2
            i = 0
        else:
              
            # next number goes out of
            # right side of square 
            if j == n:
                j = 0
                  
            # next number goes 
            # out of upper side
            if i < 0:
                i = n - 1
                  
        if magicSquare[int(i)][int(j)]: # 2nd condition
            j = j - 2
            i = i + 1

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#

// C# program to generate odd sized magic squares


using System;
  
class GFG {
      
    // Function to generate odd sized magic squares
    static void generateSquare(int n)
    {
        int[, ] magicSquare = new int[n, n];
          
        // Initialize position for 1
        int i = n / 2;
        int j = n - 1;

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

// Works only when n is odd


$n = 7; 
generateSquare ($n);
      
// This code is contributed by mits.
?>

Output:

The Magic Square for n=7:


Sum of each row or column 175:

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

NOTE: This approach works only for odd values of n.


References:
http://en.wikipedia.org/wiki/Magic_square
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above
Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/magic-square/

972
Chapter 138

Magic Square | Even Order

Magic Square | Even Order - GeeksforGeeks


A magic square of order n is an arrangement of n^2 numbers, usually distinct integers, in
a square, such that the n numbers in all rows, all columns, and both diagonals sum to the
same constant. A magic square contains the integers from 1 to n^2.
The constant sum in every row, column and diagonal is called the magic constant or magic
sum, M. The magic constant of a normal magic square depends only on n and has the
following value:
M = n (n^2 + 1) / 2.
Examples:

Magic Square of order 3:


-----------------------
2 7 6
9 5 1
4 3 8

Magic Square of order 4:


-----------------------
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

Magic Square of order 8:


-----------------------
64 63 3 4 5 6 58 57
56 55 11 12 13 14 50 49
17 18 46 45 44 43 23 24
25 26 38 37 36 35 31 32

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 :

define an 2-D array of order n*n


// fill array with their index-counting
// starting from 1
for ( i = 0; i<n; i++)
{
for ( j = 0; j<n; j++)
// filling array with its count value
// starting from 1;
arr[i][j] = (n*i) + j + 1;
}

// change value of Array elements


// at fix location as per rule
// (n*n+1)-arr[i][j]
// Top Left corner of Matrix
// (order (n/4)*(n/4))
for ( i = 0; i<n/4; i++)
{
for ( j = 0; j<n/4; j++)
arr[i][j] = (n*n + 1) - arr[i][j];
}

// Top Right corner of Matrix


// (order (n/4)*(n/4))
for ( i = 0; i< n/4; i++)
{
for ( j = 3* (n/4); j<n; j++)
arr[i][j] = (n*n + 1) - arr[i][j];
}

// Bottom Left corner of Matrix


// (order (n/4)*(n/4))
for ( i = 3* n/4; i<n; i++)

974
Chapter 138. Magic Square | Even Order

{
for ( j = 0; j<n/4; j++)
arr[i][j] = (n*n + 1) - arr[i][j];
}

// Bottom Right corner of Matrix


// (order (n/4)*(n/4))
for ( i = 3* n/4; i<n; i++)
{
for ( j = 3* n/4; j<n; j++)
arr[i][j] = (n*n + 1) - arr[i][j];
}

// Centre of Matrix (order (n/2)*(n/2))


for ( i = n/4; i<3* n/4; i++)
{
for ( j = n/4; j<3* n/4; j++)
arr[i][j] = (n*n + 1) - arr[i][j];
}

Explaination with an example:(order 4)


1) Define array of order 4*4 and fill it with its count value as:

2) Change value of top-left corner matrix of order (1*1):

3) Change value of top-right corner matrix of order (1*1):

975
Chapter 138. Magic Square | Even Order

4) Change value of bottom-left corner matrix of order (1*1):

5) Change value of bottom-right corner matrix of order (1*1):

6) Change value of centre matrix of order (2*2):

Implementation for Doubly-even Magic Square:

C/C++

// C++ Program to print Magic square

976
Chapter 138. Magic Square | Even Order

// of Doubly even order


#include<iostream>
using namespace std;
  
// Function for calculating Magic square 
void doublyEven( int n )

    int arr[n][n], i, j;
  
    // filling matrix with its count value 
    // starting from 1;
    for ( i = 0; i < n; i++)
        for ( j = 0; j < n; j++)
            arr[i][j] = (n*i) + j + 1;
       
    // change value of Array elements
    // at fix location as per rule 
    // (n*n+1)-arr[i][j]
    // Top Left corner of Matrix 
    // (order (n/4)*(n/4))
    for ( i = 0; i < n/4; i++)
        for ( j = 0; j < n/4; j++)
            arr[i][j] = (n*n + 1) - arr[i][j];
     
    // Top Right corner of Matrix 
    // (order (n/4)*(n/4))
    for ( i = 0; i < n/4; i++)
        for ( j = 3 * (n/4); j < n; j++)
            arr[i][j] = (n*n + 1) - arr[i][j];
      
     // Bottom Left corner of Matrix
    // (order (n/4)*(n/4))
    for ( i = 3 * n/4; i < n; i++)
        for ( j = 0; j < n/4; j++)
            arr[i][j] = (n*n+1) - arr[i][j];
     
    // Bottom Right corner of Matrix 
    // (order (n/4)*(n/4))
    for ( i = 3 * n/4; i < n; i++)
        for ( j = 3 * n/4; j < n; j++)
            arr[i][j] = (n*n + 1) - arr[i][j];
    
    // Centre of Matrix (order (n/2)*(n/2))
    for ( i = n/4; i < 3 * n/4; i++)
        for ( j = n/4; j < 3 * n/4; j++)
            arr[i][j] = (n*n + 1) - arr[i][j];
  
    // Printing the magic-square

977
Chapter 138. Magic Square | Even Order

    for (i = 0; i < n; i++)


    {
        for ( j = 0; j < n; j++)
            cout << arr[i][j] << " ";
        cout << "\n";
    }
}
  
// driver program
int main()
{
    int n=8;
    doublyEven(n); //Function call
    return 0;

Java

// Java program to print Magic square


// of Doubly even order
import java.io.*;
  
class GFG 
{
    // Function for calculating Magic square
    static void doublyEven(int n)
    {
        int[][] arr = new int[n][n];
        int i, j;
   
        // filling matrix with its count value 
        // starting from 1;
        for ( i = 0; i < n; i++)
            for ( j = 0; j < n; j++)
                arr[i][j] = (n*i) + j + 1;
        
        // change value of Array elements
        // at fix location as per rule 
        // (n*n+1)-arr[i][j]
        // Top Left corner of Matrix 
        // (order (n/4)*(n/4))
        for ( i = 0; i < n/4; i++)
            for ( j = 0; j < n/4; j++)
                arr[i][j] = (n*n + 1) - arr[i][j];
      
        // Top Right corner of Matrix 
        // (order (n/4)*(n/4))
        for ( i = 0; i < n/4; i++)

978
Chapter 138. Magic Square | Even Order

            for ( j = 3 * (n/4); j < n; j++)


                arr[i][j] = (n*n + 1) - arr[i][j];
       
        // Bottom Left corner of Matrix
        // (order (n/4)*(n/4))
        for ( i = 3 * n/4; i < n; i++)
            for ( j = 0; j < n/4; j++)
                arr[i][j] = (n*n+1) - arr[i][j];
      
        // Bottom Right corner of Matrix 
        // (order (n/4)*(n/4))
        for ( i = 3 * n/4; i < n; i++)
            for ( j = 3 * n/4; j < n; j++)
                arr[i][j] = (n*n + 1) - arr[i][j];
     
        // Centre of Matrix (order (n/2)*(n/2))
        for ( i = n/4; i < 3 * n/4; i++)
            for ( j = n/4; j < 3 * n/4; j++)
                arr[i][j] = (n*n + 1) - arr[i][j];
   
        // Printing the magic-square
        for (i = 0; i < n; i++)
        {
            for ( j = 0; j < n; j++)
                System.out.print(arr[i][j]+" ");
            System.out.println();
        }
    }
      
    // driver program
    public static void main (String[] args) 
    {
        int n = 8;
        // Function call
        doublyEven(n);
    }
}
  
// Contributed by Pramod Kumar

Python

# Python program to print magic square of double order


  
def DoublyEven(n):
      
    # 2-D matrix with all entries as 0
    arr = [[(n*y)+x+1 for x in range(n)]for y in range(n)]

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

Time complexity : O(n^2)


Reference: http://www.1728.org/magicsq2.html

Source

https://www.geeksforgeeks.org/magic-square-even-order/

981
Chapter 139

Matrix Chain Multiplication |


DP-8

Matrix Chain Multiplication | DP-8 - GeeksforGeeks


Given a sequence of matrices, find the most efficient way to multiply these matrices together.
The problem is not actually to perform the multiplications, but merely to decide in which
order to perform the multiplications.
We have many options to multiply a chain of matrices because matrix multiplication is
associative. In other words, no matter how we parenthesize the product, the result will be
the same. For example, if we had four matrices A, B, C, and D, we would have:

(ABC)D = (AB)(CD) = A(BCD) = ....

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,

(AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations


A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.

Clearly the first parenthesization requires less number of operations.


Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of
dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return
the minimum number of multiplications needed to multiply the chain.

Input: p[] = {40, 20, 30, 10, 30}


Output: 26000
There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
Let the input 4 matrices be A, B, C and D. The minimum number of

982
Chapter 139. Matrix Chain Multiplication | DP-8

multiplications are obtained by putting parenthesis in following way


(A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30

Input: p[] = {10, 20, 30, 40, 30}


Output: 30000
There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30.
Let the input 4 matrices be A, B, C and D. The minimum number of
multiplications are obtained by putting parenthesis in following way
((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30

Input: p[] = {10, 20, 30}


Output: 6000
There are only two matrices of dimensions 10x20 and 20x30. So there
is only one way to multiply the matrices, cost of which is 10*20*30

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.

/* A naive recursive implementation that simply


  follows the above optimal substructure property */
#include<stdio.h>
#include<limits.h>
  
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
int MatrixChainOrder(int p[], int i, int j)
{
    if(i == j)
        return 0;
    int k;
    int min = INT_MAX;
    int count;
  
    // place parenthesis at different places between first

983
Chapter 139. Matrix Chain Multiplication | DP-8

    // and last matrix, recursively calculate count of


    // multiplications for each parenthesis placement and
    // return the minimum count
    for (k = i; k <j; k++)
    {
        count = MatrixChainOrder(p, i, k) +
                MatrixChainOrder(p, k+1, j) +
                p[i-1]*p[k]*p[j];
  
        if (count < min)
            min = count;
    }
  
    // Return minimum count
    return min;
}
  
// Driver program to test above function
int main()
{
    int arr[] = {1, 2, 3, 4, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    printf("Minimum number of multiplications is %d ",
                          MatrixChainOrder(arr, 1, n-1));
  
    getchar();
    return 0;
}

Java

/* A naive recursive implementation that simply follows


   the above optimal substructure property */
class MatrixChainMultiplication
{
    // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
    static int MatrixChainOrder(int p[], int i, int j)
    {
        if (i == j)
            return 0;
  
        int min = Integer.MAX_VALUE;
  
        // place parenthesis at different places between first
        // and last matrix, recursively calculate count of
        // multiplications for each parenthesis placement and
        // return the minimum count

984
Chapter 139. Matrix Chain Multiplication | DP-8

        for (int k=i; k<j; k++)


        {
            int count = MatrixChainOrder(p, i, k) +
                        MatrixChainOrder(p, k+1, j) +
                        p[i-1]*p[k]*p[j];
  
            if (count < min)
                min = count;
        }
  
        // Return minimum count
        return min;
    }
  
    // Driver program to test above function
    public static void main(String args[])
    {
        int arr[] = new int[] {1, 2, 3, 4, 3};
        int n = arr.length;
  
        System.out.println("Minimum number of multiplications is "+
                           MatrixChainOrder(arr, 1, n-1));
  
    }
}
/* This code is contributed by Rajat Mishra*/

Python3

# A naive recursive implementation that


# simply follows the above optimal 
# substructure property 
import sys
  
# Matrix A[i] has dimension p[i-1] x p[i]
# for i = 1..n
def MatrixChainOrder(p, i, j):
  
    if i == j:
        return 0
  
    _min = sys.maxsize
      
    # place parenthesis at different places 
    # between first and last matrix, 
    # recursively calculate count of
    # multiplications for each parenthesis
    # placement and return the minimum count

985
Chapter 139. Matrix Chain Multiplication | DP-8

    for k in range(i, j):


      
        count = (MatrixChainOrder(p, i, k) 
             + MatrixChainOrder(p, k+1, j)
                   + p[i-1] * p[k] * p[j])
  
        if count < _min:
            _min = count;
      
  
    # Return minimum count
    return _min;
  
  
# Driver program to test above function
arr = [1, 2, 3, 4, 3];
n = len(arr);
  
print("Minimum number of multiplications is ",
                MatrixChainOrder(arr, 1, n-1));
  
# This code is contributed by Aryan Garg

C#

/* C# code for naive recursive implementation 


that simply follows the above optimal 
substructure property */
using System;
  
class GFG {
      
    // Matrix Ai has dimension p[i-1] x p[i]
    // for i = 1..n
    static int MatrixChainOrder(int[] p, int i, int j)
    {
          
        if (i == j)
            return 0;
  
        int min = int.MaxValue;
  
        // place parenthesis at different places 
        // between first and last matrix, recursively 
        // calculate count of multiplications for each
        // parenthesis placement and return the 
        // minimum count
        for (int k = i; k < j; k++) {

986
Chapter 139. Matrix Chain Multiplication | DP-8

            int count = MatrixChainOrder(p, i, k) +


            MatrixChainOrder(p, k + 1, j) + p[i - 1] 
                                       * p[k] * p[j];
  
            if (count < min)
                min = count;
        }
  
        // Return minimum count
        return min;
    }
  
    // Driver program to test above function
    public static void Main()
    {
        int[] arr = new int[]{ 1, 2, 3, 4, 3 };
        int n = arr.Length;
  
        Console.Write("Minimum number of multiplications is "
                          + MatrixChainOrder(arr, 1, n - 1));
    }
}
  
// This code is contributed by Sam007.

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.

// See the Cormen book for details of the following algorithm


#include<stdio.h>
#include<limits.h>
  
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
int 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[][] are not used */
    int m[n][n];
  
    int i, j, k, L, q;
  
    /* 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;
            m[i][j] = INT_MAX;
            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;

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

// Dynamic Programming Python implementation of Matrix


// Chain Multiplication.
// See the Cormen book for details of the following algorithm
class MatrixChainMultiplication
{
    // Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
    static int 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[][] are not used */
        int m[][] = new int[n][n];
  
        int i, j, k, L, q;
  
        /* 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++)

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

# Dynamic Programming Python implementation of Matrix


# Chain Multiplication. See the Cormen book for details
# of the following algorithm
import sys
  
# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
def MatrixChainOrder(p, n):
    # For simplicity of the program, one extra row and one
    # extra column are allocated in m[][].  0th row and 0th
    # column of m[][] are not used
    m = [[0 for x in range(n)] for x in range(n)]
  
    # 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.

990
Chapter 139. Matrix Chain Multiplication | DP-8

    for i in range(1, n):


        m[i][i] = 0
  
    # L is chain length.
    for L in range(2, n):
        for i in range(1, n-L+1):
            j = i+L-1
            m[i][j] = sys.maxint
            for k in range(i, j):
  
                # 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
arr = [1, 2, 3 ,4]
size = len(arr)
  
print("Minimum number of multiplications is " +
       str(MatrixChainOrder(arr, size)))
# This Code is contributed by Bhavya Jain

C#

// Dynamic Programming C# implementation of 


// Matrix Chain Multiplication.
// See the Cormen book for details of the 
// following algorithm
using System;
  
class GFG
{
      
    // Matrix Ai has dimension p[i-1] x p[i] 
    // for i = 1..n
    static int 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[][] are not used */
        int [ , ]m = new int[n, n];
  
        int i, j, k, L, q;

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:

Minimum number of multiplications is 18

Time Complexity: O(n^3)


Auxiliary Space: O(n^2)
Printing brackets in Matrix Chain Multiplication Problem
Applications:
Minimum and Maximum values of an expression with * and +
References:
http://en.wikipedia.org/wiki/Matrix_chain_multiplication
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Dynamic/
chainMatrixMult.htm
Improved By : aryan21

Source

https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/

993
Chapter 140

Matrix Exponentiation

Matrix Exponentiation - GeeksforGeeks


This is one of the most used techniques in competitive programming. Let us first consider
below simple question.
What is the minimum time complexity to find n’th Fibonacci Number?
We can find n’th Fibonacci Number in O(Log n) time using Matrix Exponentiation. Refer
method 4 of this for details. In this post, a general implementation of Matrix Exponentiation
is discussed.

For solving the matrix exponentiation we are assuming a


linear recurrence equation like below:

F(n) = a*F(n-1) + b*F(n-2) + c*F(n-3) for n >= 3


. . . . . Equation (1)
where a, b and c are constants.

For this recurrence relation it depends on three previous values.


Now we will try to represent Equation (1) in terms of matrix.

[First Matrix] = [Second matrix] * [Third Matrix]


| F(n) | = Matrix 'C' * | F(n-1) |
| F(n-1) | | F(n-2) |
| F(n-2) | | F(n-3) |

Dimension of the first matrix is 3 x 1 .


Dimension of third matrix is also 3 x 1.

So the dimension of the second matrix must be 3 x 3


[For multiplication rule to be satisfied.]

Now we need to fill the Matrix 'C'.

994
Chapter 140. Matrix Exponentiation

So according to our equation.


F(n) = a*F(n-1) + b*F(n-2) + c*F(n-3)
F(n-1) = F(n-1)
F(n-2) = F(n-2)

C = [a b c
1 0 0
0 1 0]

Now the relation between matrix becomes :


[First Matrix] [Second matrix] [Third Matrix]
| F(n) | = | a b c | * | F(n-1) |
| F(n-1) | | 1 0 0 | | F(n-2) |
| F(n-2) | | 0 1 0 | | F(n-3) |

Lets assume the initial values for this case :-


F(0) = 0
F(1) = 1
F(2) = 1

So, we need to get F(n) in terms of these values.

So, for n = 3 Equation (1) changes to


| F(3) | = | a b c | * | F(2) |
| F(2) | | 1 0 0 | | F(1) |
| F(1) | | 0 1 0 | | F(0) |

Now similarly for n = 4


| F(4) | = | a b c | * | F(3) |
| F(3) | | 1 0 0 | | F(2) |
| F(2) | | 0 1 0 | | F(1) |

- - - - 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) |

So for n, the Equation (1) changes to

- - - - - - - - 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) |

| F(n) | = [ | a b c | ] ^ (n-2) * | F(2) |


| F(n-1) | [ | 1 0 0 | ] | F(1) |

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

We can find n’th term using following :

Putting a = 1, b = 1 and c = 1 in above formula

| F(n) | = [ | 1 1 1 | ] ^ (n-2) * | F(2) |


| F(n-1) | [ | 1 0 0 | ] | F(1) |
| F(n-2) | [ | 0 1 0 | ] | F(0) |

Below is the implementation of above idea.


C++

// C++ program to find value of f(n) where 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
#include<bits/stdc++.h>
using namespace std;
  
// A utility function to multiply two matrices
// a[][] and b[][].  Multiplication result is
// stored back in b[][]
void multiply(int a[3][3], int b[3][3])
{
    // Creating an auxiliary matrix to store elements 
    // of the multiplication matrix
    int mul[3][3];
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            mul[i][j] = 0;
            for (int k = 0; k < 3; k++)

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

// JAVA program to find value of f(n) where


// 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
import java.io.*;
  
class GFG {
      
    // A utility function to multiply two 
    // matrices a[][] and b[][]. 
    // Multiplication result is
    // stored back in b[][]
    static void multiply(int a[][], int b[][])
    {
        // Creating an auxiliary matrix to 
        // store elements of the 
        // multiplication matrix
        int mul[][] = new int[3][3];
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                mul[i][j] = 0;
                for (int k = 0; k < 3; k++)
                    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++)
              
                // Updating our matrix
                a[i][j] = mul[i][j]; 
    }
      

998
Chapter 140. Matrix Exponentiation

    // Function to compute F raise to


    // power n-2.
    static int power(int F[][], int n)
    {
        int M[][] = {{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
    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 (String[] args) {
          
        int n = 5;
          
        System.out.println("F(5) is "
                           + findNthTerm(n));
    }

999
Chapter 140. Matrix Exponentiation

}
  
//This code is contributed by vt_m.

C#

// C# program to find value of f(n) where 


// 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
using System;
  
class GFG {
  
    // A utility function to multiply two 
    // matrices a[][] and b[][]. Multiplication
    // result is stored back in b[][]
    static void multiply(int[, ] a, int[, ] b)
    {
          
        // Creating an auxiliary matrix to store 
        // elements of the multiplication matrix
        int[, ] mul = new int[3, 3];
          
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                mul[i, j] = 0;
                for (int k = 0; k < 3; k++)
                    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++)
              
                // Updating our matrix
                a[i, j] = mul[i, j]; 
    }
  
    // Function to compute F raise to power n-2.
    static int power(int[, ] F, int n)
    {
          
        int[, ] M = { { 1, 1, 1 }, { 1, 0, 0 }, 
                                   { 0, 1, 0 } };

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

Time Complexity of this solution : O(log n)


This article is contributed by Abhiraj Smit. 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/matrix-exponentiation/

1002
Chapter 141

Matrix Multiplication |
Recursive

Matrix Multiplication | Recursive - GeeksforGeeks


Given two matrices A and B. The task is to multiply matrix A and matrix B recursively.
If matrix A and matrix B are not multiplicative compatible, then generate output “Not
Possible”.
Examples :

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

It is recommended to first refer Iterative Matrix Multiplication.


First check if multiplication between matrices is possible or not. For this, check if number

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++

// Recursive code for Matrix Multiplication


#include <stdio.h>
  
const int MAX = 100;
  
void multiplyMatrixRec(int row1, int col1, int A[][MAX],
                       int row2, int col2, int B[][MAX],
                       int C[][MAX])
{
    // Note that below variables are static
    // i and j are used to know current cell of
    // result matrix C[][]. k is used to know
    // current column number of A[][] and row
    // number of B[][] to be multiplied
    static int i = 0, j = 0, k = 0;
  
    // If all rows traversed.
    if (i >= row1)
        return;
  
    // If i < row1
    if (j < col2)
    {
      if (k < col1)
      {
         C[i][j] += A[i][k] * B[k][j];
         k++;
  
         multiplyMatrixRec(row1, col1, A, row2, col2,
                                               B, C);
      }
  
      k = 0;
      j++;
      multiplyMatrixRec(row1, col1, A, row2, col2, B, 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

// Java recursive code for Matrix Multiplication


  
class GFG 
{
    public static int MAX = 100;
      
    // Note that below variables are static
    // i and j are used to know current cell of
    // result matrix C[][]. k is used to know
    // current column number of A[][] and row
    // number of B[][] to be multiplied
    public static int i = 0, j = 0, k = 0;
      
    static void multiplyMatrixRec(int row1, int col1, int A[][],
                       int row2, int col2, int B[][],
                       int C[][])
    {
        // If all rows traversed
        if (i >= row1)
            return;
   
        // If i < row1
        if (j < col2)
        {
            if (k < col1)
            {
                C[i][j] += A[i][k] * B[k][j];
                k++;
   
                multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
            }
   
            k = 0;
            j++;
            multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
        }
   
        j = 0;
        i++;
        multiplyMatrixRec(row1, col1, A, row2, col2, B, C);
    }
   
    // Function to multiply two matrices A[][] and B[][]
    static void multiplyMatrix(int row1, int col1, int A[][],
                    int row2, int col2, int B[][])
    {
        if (row2 != col1)
        {

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#

// C# recursive code for 


// Matrix Multiplication
using System;
  
class GFG
{
    public static int MAX = 100;
      
    // Note that below variables
    // are static i and j are used 

1007
Chapter 141. Matrix Multiplication | Recursive

    // to know current cell of result 


    // matrix C[][]. k is used to
    // know current column number of 
    // A[][] and row number of B[][]
    // to be multiplied
    public static int i = 0, j = 0, k = 0;
      
    static void multiplyMatrixRec(int row1, int col1, 
                                  int [,]A, int row2, 
                                  int col2, int [,]B,
                                  int [,]C)
    {
        // If all rows traversed
        if (i >= row1)
            return;
  
        // If i < row1
        if (j < col2)
        {
            if (k < col1)
            {
                C[i, j] += A[i, k] * B[k, j];
                k++;
  
                multiplyMatrixRec(row1, col1, A, 
                                  row2, col2, B, C);
            }
  
            k = 0;
            j++;
            multiplyMatrixRec(row1, col1, A, 
                              row2, col2, B, C);
        }
  
        j = 0;
        i++;
        multiplyMatrixRec(row1, col1, A, 
                          row2, col2, B, C);
    }
  
    // Function to multiply two
    // matrices A[][] and B[][]
    static void multiplyMatrix(int row1, int col1, 
                               int [,]A, int row2, 
                               int col2, int [,]B)
    {
        if (row2 != col1)
        {

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

Matrix manipulation in Python

Matrix manipulation in Python - GeeksforGeeks


In python matrix can be implemented as 2D list or 2D Array. Forming matrix from lat-
ter, gives the additional functionalities for performing various operations in matrix. These
operations and array are defines in module “numpy“.
Operation on Matrix :
1. add() :- This function is used to perform element wise matrix addition.
2. subtract() :- This function is used to perform element wise matrix subtraction.
3. divide() :- This function is used to perform element wise matrix division.

# Python code to demonstrate matrix operations


# add(), subtract() and divide()
  
# importing numpy for matrix operations
import numpy
  
# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
  
# using add() to add matrices
print ("The element wise addition of matrix is : ")
print (numpy.add(x,y))
  
# using subtract() to subtract matrices
print ("The element wise subtraction of matrix is : ")
print (numpy.subtract(x,y))
  
# using divide() to divide matrices
print ("The element wise division of matrix is : ")
print (numpy.divide(x,y))

1011
Chapter 142. Matrix manipulation in Python

Output :

The element wise addition of matrix is :


[[ 8 10]
[13 15]]
The element wise subtraction of matrix is :
[[-6 -6]
[-5 -5]]
The element wise division of matrix is :
[[ 0.14285714 0.25 ]
[ 0.44444444 0.5 ]]

4. multiply() :- This function is used to perform element wise matrix multiplication.


5. dot() :- This function is used to compute the matrix multiplication, rather than
element wise multiplication.

# Python code to demonstrate matrix operations


# multiply() and dot()
  
# importing numpy for matrix operations
import numpy
  
# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
  
# using multiply() to multiply matrices element wise
print ("The element wise multiplication of matrix is : ")
print (numpy.multiply(x,y))
  
# using dot() to multiply matrices
print ("The product of matrices is : ")
print (numpy.dot(x,y))

Output :

The element wise multiplication of matrix is :


[[ 7 16]
[36 50]]
The product of matrices is :
[[25 28]
[73 82]]

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.

# Python code to demonstrate matrix operations


# sqrt(), sum() and "T"
  
# importing numpy for matrix operations
import numpy
  
# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
  
# using sqrt() to print the square root of matrix
print ("The element wise square root is : ")
print (numpy.sqrt(x))
  
# using sum() to print summation of all elements of matrix
print ("The summation of all matrix element is : ")
print (numpy.sum(y))
  
# using sum(axis=0) to print summation of all columns of matrix
print ("The column wise summation of all matrix  is : ")
print (numpy.sum(y,axis=0))
  
# using sum(axis=1) to print summation of all columns of matrix
print ("The row wise summation of all matrix  is : ")
print (numpy.sum(y,axis=1))
  
# using "T" to transpose the matrix
print ("The transpose of given matrix is : ")
print (x.T)

Output :

The element wise square root is :


[[ 1. 1.41421356]
[ 2. 2.23606798]]
The summation of all matrix element is :
34
The column wise summation of all matrix is :
[16 18]
The row wise summation of all matrix is :
[15 19]
The transpose of given matrix is :

1013
Chapter 142. Matrix manipulation in Python

[[1 4]
[2 5]]

Source

https://www.geeksforgeeks.org/matrix-manipulation-python/

1014
Chapter 143

Matrix sum except one item

Matrix sum except one item - GeeksforGeeks


Given a n*m matrix find the sum of the elements of the matrix without the element specified
by its position
Examples:

Input : mat[] = {{1 2 4},


{5 6 8}}
cell = (0 2)
Output :22
We need to find sum of all elements
except mat[0][2].

Input : mat[][] = {{5 6 2 3}, {2 3 1 8}, {9 6 5 2}}


cell = (1 2)
Output :51

A simple solution is to traverse through matrix. For every visited cell, check if it is the
cell to be ignored.
C++

// C++ program to find sum 


// of matrix except cell (x, y)
#include<bits/stdc++.h>
using namespace std;
  
// Dimension of input matrix
# define R 2
# define C 3
  

1015
Chapter 143. Matrix sum except one item

// Returns sum of arr[][]


// except cell arr[x][y]
int calcSum(int arr[R][C], 
            int x, int y)
{
    int sum = 0;
    for (int i = 0; i < R; i++)
    {
        for (int j = 0; j < C; j++)
        {
            if (i != x || j != y)
                sum = sum + arr[i][j];
        }
    }
    return sum;
}
  
// Driver code
int main()
{
    int x = 0, y = 2;
    int arr[R][C] = {1, 2, 4, 
                     5, 6, 8 };
                      
    cout << calcSum(arr, x, y);
}
  
// This code is contributed 
// by ChitraNayal

Java

// Java program to find sum of matrix except 


// cell (x, y)
class Matrix {
  
    // Returns sum of arr[][] except cell arr[x][y]
    static int calcSum(int[][] arr, int x, int y)
    {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
              if (i != x || j != y)
                sum = sum + arr[i][j];
            }
        }
        return sum;
    }

1016
Chapter 143. Matrix sum except one item

    public static void main(String[] args)


    {
        int x = 0, y = 2;
        int[][] arr = {
            { 1, 2, 4 }, { 5, 6, 8 },
        };
        System.out.println(calcSum(arr, x, y));
    }
}

C#

// C# program to find sum 


// of matrix except cell (x, y)
using System;
  
class GFG 
{
  
    // Returns sum of arr[,] 
    // except cell arr[x][y]
    static int calcSum(int[,] arr,
                       int x, int y)
    {
        int sum = 0;
        for (int i = 0; 
                 i < arr.GetLength(0); i++) 
        {
            for (int j = 0; 
                     j < arr.GetLength(1); j++) 
            {
            if (i != x || j != y)
                sum = sum + arr[i, j];
            }
        }
        return sum;
    }
      
    // Driver Code
    public static void Main()
    {
        int x = 0, y = 2;
        int[,] arr = {{ 1, 2, 4 }, 
                      { 5, 6, 8 }};
        Console.Write(calcSum(arr, x, y));
    }
}
  

1017
Chapter 143. Matrix sum except one item

// This code is contributed


// by ChitraNayal

Python 3

# Python 3 program to find 


# sum of matrix except cell (x, y)
  
# Returns sum of arr[][]
# except cell arr[x][y]
def calcSum(arr, x, y):
    s = 0
    for i in range(R):
        for j in range(C):
            if (i != x or j != y):
                s = s + arr[i][j];
    return s;
  
# Driver code
x = 0
y = 2
arr = [[ 1, 2, 4 ],
       [ 5, 6, 8 ]]
R = 2
C = 3
  
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++) 

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++

// C++ program to find sum 


// of matrix except cell (x, y)
#include<bits/stdc++.h>
using namespace std;
  
#define R 2
#define C 3
  
// Returns sum of arr[][] 
// except cell arr[x][y]
int calcSum(int arr[R][C], 
            int x, int y)
{
    int sum = 0;
    for (int i = 0; i < R; i++) 
        for (int j = 0; j < C; j++) 

1019
Chapter 143. Matrix sum except one item

            sum = sum + arr[i][j];


  
    return sum - arr[x][y];
}
  
// Driver code
int main()
{
    int x = 0, y = 2;
    int arr[R][C]= {1, 2, 4 ,
                    5, 6, 8 };
  
    cout << (calcSum(arr, x, y));
}
  
// This code is contributed
// by ChitraNayal

Java

// Java program to find sum of matrix except 


// cell (x, y)
class Matrix {
  
    // Returns sum of arr[][] except cell arr[x][y]
    static int calcSum(int[][] arr, int x, int y)
    {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) 
            for (int j = 0; j < arr[i].length; j++) 
                sum = sum + arr[i][j];
  
        return sum - arr[x][y];
    }
  
    public static void main(String[] args)
    {
        int x = 0, y = 2;
        int[][] arr = {
            { 1, 2, 4 }, { 5, 6, 8 },
        };
        System.out.println(calcSum(arr, x, y));
    }
}

C#

// C# program to find sum 

1020
Chapter 143. Matrix sum except one item

// of matrix except cell (x, y)


using System;
  
class GFG 
{
  
    // Returns sum of arr[,]
    // except cell arr[x,y]
    static int calcSum(int[,] arr, 
                       int x, int y)
    {
        int sum = 0;
        for (int i = 0; 
                 i < arr.GetLength(0); i++) 
            for (int j = 0; 
                     j < arr.GetLength(1); j++) 
                sum = sum + arr[i, j];
  
        return sum - arr[x, y];
    }
  
    // Driver code
    public static void Main()
    {
        int x = 0, y = 2;
        int[,] arr = {{ 1, 2, 4 }, 
                      { 5, 6, 8 }};
        Console.Write(calcSum(arr, x, y));
    }
}
  
// This code is contributed
// by ChitraNayal

Python 3

# Python 3 program to find 


# sum of matrix except cell (x, y)
  
# Returns sum of arr[][] 
# except cell arr[x][y]
def calcSum( arr, x, y):
    s = 0
    for i in range(R): 
        for j in range(C): 
            s = s + arr[i][j]
  
    return s - arr[x][y]

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

Maximize matrix as per given


condition

Maximize matrix as per given condition - GeeksforGeeks


You are given a N*N matrix, where each element of matrix lies in the range 0 to M. You
can apply the below operation on matrix any number of times:

• Choose any two consecutive elements


• Increment one of them by 1 and decrease other by 1

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]

for 0 <= i, j <= N

Examples:

Input : A[][] = {1, 2,


5, 1}
M = 5
Output : RESULT = 27
Matrix : 0 0
4 5

Input : A[][] = {3, 4,

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:

Solution Matrix after applying above algorithm :

1025
Chapter 144. Maximize matrix as per given condition

Below is the implementation of above idea :

C++

// CPP to maximize matrix result


#include<bits/stdc++.h>
using namespace std;
#define n 4
  
// utility function for maximize matrix result
int maxMatrix(int A[][n], int M)
{
    int sum = 0, res = 0;
    for ( int i=0; i<n ; i++)
        for ( int j=0; j<n; j++)
            sum += A[i][j];
  
    // diagonals below longest diagonal
    // starting from last element of matrix
    for (int j=n-1; j>0; j--)
    {
        for (int i=0; i<n-j; i++)
        {
            if (sum > M)
            {

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

Maximize sum of N X N upper


left sub-matrix from given 2N X
2N matrix

Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix - GeeksforGeeks


Given a 2N x 2N matrix of integers. You are allowed to reverse any row or column any
number of times and in any order. The task is to calculate the maximum sum of the upper-
left N X N submatrix i.e the sum of elements of submatrix from (0, 0) to (N – 1, N –
1).
Examples:

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

119, 114, 42, 112,


56, 125, 101, 49,
15, 78, 56, 43,
62, 98, 83, 108

Sum of upper-left matrix = 119 + 114 + 56 + 125 = 414.

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

Below is C++ implementation of this approach:

// C++ program to find maximum value of top N/2 x N/2


// matrix using row and column reverse operations
#include<bits/stdc++.h>
#define R 4
#define C 4
using namespace std;
  
int maxSum(int mat[R][C])
{
  int sum = 0;
  
  for (int i = 0; i < R/2; i++)

1037
Chapter 145. Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix

    for (int j = 0; j < C/2; j++) 


    {
      int r1 = i;
      int r2 = R - i - 1;
      int c1 = j;
      int c2 = C - j - 1;
        
      // We can replace current cell [i, j]
      // with 4 cells without changing affecting
      // other elements.
      sum += max(max(mat[r1][c1], mat[r1][c2]), 
                 max(mat[r2][c1], mat[r2][c2]));
    }
      
    return sum;
}
  
// Driven Program
int main() 
{
  int mat[R][C] = {
                    112, 42, 83, 119,
                    56, 125, 56, 49,
                    15, 78, 101, 43,
                    62, 98, 114, 108
                  };
  
  cout << maxSum(mat) << endl;
  
  return 0;
}

Output:

414

Time Complexity: O(N2 ).

Source

https://www.geeksforgeeks.org/maximize-sum-n-x-n-upper-left-sub-matrix-given-2n-x-2n-matrix/

1038
Chapter 146

Maximize the binary matrix by


filpping submatrix once

Maximize the binary matrix by filpping submatrix once - GeeksforGeeks


Given a binary matrix of R rows and C columns. We are allowed flip to any size of sub
matrix. Flipping means changing 1 to 0 and 0 to 1. The task is maximize the number of 1s
in the matrix. Output the maximum number of 1s.
Examples:

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

// Common elements in ones[i-1][j] and


// ones[i][j-1] are ones[i-1][j-1]
ones[i][j] = ones[i-1][j] + ones[i][j-1] -
ones[i-1][j-1] + (mat[i][j] == 1)

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:

// C++ program to find maximum number of ones after


// one flipping in Binary Matrix
#include <bits/stdc++.h>
#define R 3
#define C 3
using namespace std;
  
// Return number of ones in square submatrix of size
// k x k starting from (x, y)
int cal(int ones[R + 1][C + 1], int x, int y, int k)
{
    return ones[x + k - 1][y + k - 1] - ones[x - 1][y + k - 1]
           - ones[x + k - 1][y - 1] + ones[x - 1][y - 1];
}
  
// Return maximum number of 1s after flipping a submatrix
int sol(int mat[R][C])
{
    int ans = 0;
  
    // Precomputing the number of 1s
    int ones[R + 1][C + 1] = {0};
    for (int i = 1; i <= R; i++)
        for (int j = 1; j <= C; j++)
            ones[i][j] = ones[i - 1][j] + ones[i][j - 1] -

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:

Time Complexity: O(R*C*min(R, C))

Source

https://www.geeksforgeeks.org/maximize-binary-matrix-filpping-submatrix/

1041
Chapter 147

Maximum XOR value in matrix

Maximum XOR value in matrix - GeeksforGeeks


Given a square matrix (N X N), the task is to find the maximum XOR value of a complete
row or a complete column.
Examples :

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

2. Store the maximum of both.

Below is the implementation :

C++

// C++ program to Find maximum XOR value in


// matrix either row / column wise
#include<iostream>
using namespace std;
  
// maximum number of row and column
const int MAX = 1000;
  
// function return the maximum xor value that is
// either row or column wise
int maxXOR(int mat[][MAX], int N)
{
    // for row xor and column xor
    int r_xor, c_xor;
    int max_xor = 0;
  
    // 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 < max(r_xor, c_xor))
            max_xor = max(r_xor, c_xor);
    }
  
    // return maximum xor value
    return max_xor;
}
  
// driver Code
int main()

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

// Java program to Find maximum XOR value in


// matrix either row / column wise
class GFG {
      
    // maximum number of row and column
    static final int MAX = 1000;
      
    // function return the maximum xor value 
    // that is either row or column wise
    static int maxXOR(int mat[][], int N)
    {
          
        // for row xor and column xor
        int r_xor, c_xor;
        int max_xor = 0;
      
        // 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

1044
Chapter 147. Maximum XOR value in matrix

            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 (String[] args)
    {
          
        int N = 3;
      
        int mat[][] = { {1, 5, 4},
                        {3, 7, 2},
                        {5, 9, 10}};
      
        System.out.print("maximum XOR value : "
            + maxXOR(mat, N));
    }
}
  
// This code is contributed by Anant Agarwal.

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#

// C# program to Find maximum XOR value in


// matrix either row / column wise
using System;
  
class GFG 
{
      
    // maximum number of row and column
  
      
    // function return the maximum xor value 
    // that is either row or column wise
    static int maxXOR(int [,]mat, int N)
    {
          
        // for row xor and column xor
        int r_xor, c_xor;
        int max_xor = 0;

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

// matrix either row or 


// column wise
  
// maximum number of 
// row and column
$MAX = 1000;
  
// function return the maximum 
// xor value that is either
// row or column wise
function maxXOR($mat, $N)
{
      
    // for row xor and 
    // column xor
    $r_xor; $c_xor;
    $max_xor = 0;
  
    // traverse matrix
    for ($i = 0 ; $i < $N ; $i++)
    {
        $r_xor = 0; $c_xor = 0;
        for ($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 < max($r_xor, $c_xor))
            $max_xor = max($r_xor, $c_xor);
    }
  
    // return maximum 
    // xor value
    return $max_xor;
}
  
    // Driver Code
    $N = 3;

1048
Chapter 147. Maximum XOR value in matrix

    $mat = array(array(1, 5, 4),


                 array(3, 7, 2),
                 array(5, 9, 10));
  
    echo "maximum XOR value : "
        , maxXOR($mat, $N);
  
// This code is contributed by anuj_67.
?>

Output :

maximum XOR value : 12

Time complexity : O(N*N)


space complexity : O(1)
Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/maximum-xor-value-matrix/

1049
Chapter 148

Maximum and Minimum Values


of an Algebraic Expression

Maximum and Minimum Values of an Algebraic Expression - GeeksforGeeks


Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn ) * (y1 + y2 + . . . +
ym ) and
(n + m) integers. Find the maximum and minimum value of the expression using the given
integers.

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

A simple solution is to consider all possible combinations of n numbers and remaining m


numbers and calculating their values, from which maximum value and minimum value can
be derived.
Below is an efficient solution.
The idea is based on limited values of n, m, x1, x2, .. y1, y2, .. Let suppose S be the sum
of all the (n + m) numbers in the expression and X be the sum of the n numbers on the
left of expression. Obviously, the sum of the m numbers on the right of expression will be
represented as (S – X). There can be many possible values of X from the given (n + m)
numbers and hence the problem gets reduced to simply iterate through all values of X and
keeping track of the minimum and maximum value of X * (S – X).
Now, the problem is equivalent to finding all possible values of X. Since the given numbers
are in the range of -50 to 50 and the maximum value of (n + m) is 100, X will lie in
between -2500 and 2500 which results into overall 5000 values of X. We will use dynamic
programming approach to solve this problem. Consider a dp[i][j] array which can value
either 1 or 0, where 1 means X can be equal to j by choosing i numbers from the (n + m)
numbers and 0 otherwise. Then for each number k, if dp[i][j] is 1 then dp[i + 1][j + k] is
also 1 where k belongs to given (n + m) numbers. Thus, by iterating through all k, we can
determine whether a value of X is reachable by choosing a total of n numbers
Below is the implementation of the above approach.

C++

// CPP program to find the maximum


// and minimum values of an Algebraic
// expression of given form
#include <bits/stdc++.h>
using namespace std;
  
#define INF 1e9
#define MAX 50
  
int minMaxValues(int arr[], int n, int m)
{
    // Finding sum of array elements
    int sum = 0;
    for (int 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 by choosing
// i numbers
bool dp[MAX+1][MAX * MAX + 1];

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

// Java program to find the maximum


// and minimum values of an Algebraic
// expression of given form
import java.io.*;
import java.lang.*;
  
public class GFG {
      
    static double INF = 1e9;
    static int MAX = 50;
  
    static void minMaxValues(int []arr, 
                              int n, int m)
    {
          
        // Finding sum of array elements
        int sum = 0;
        for (int 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 by choosing
        // i numbers
        boolean dp[][] = 
             new boolean[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

1053
Chapter 148. Maximum and Minimum Values of an Algebraic Expression

            // 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 *
                                        (sum - temp));
                                              
                min_value = Math.min(min_value, temp * 
                                        (sum - temp));
            }
        }
          
        System.out.print("Maximum Value: " + 
                     (int)max_value + "\n" + 
          "Minimum Value: " + (int)min_value + "\n");
    }
  
    // Driver Code
    public static void main(String args[])
    {
        int n = 2, m = 2;
        int []arr = { 1, 2, 3, 4 };
        minMaxValues(arr, n, m);
    }
}
  

1054
Chapter 148. Maximum and Minimum Values of an Algebraic Expression

// This code is contributed by Manish Shaw


// (manishshaw1)

Python3

# Python3 program to find the 


# maximum and minimum values 
# of an Algebraic expression 
# of given form
def minMaxValues(arr, n, m) :     
    # Finding sum of
    # array elements
    sum = 0
    INF = 1000000000
    MAX = 50
    for i in range(0, (n + m)) :
        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
    dp = [[0 for x in range(MAX * MAX + 1)]
                  for y in range( MAX + 1)]
      
    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 i in range(0, (n + m)) : 
          
        # k can be at max n because the
        # left expression has n numbers
        for k in range(min(n, i + 1), 0, -1) :
            for j in range(0, MAX * MAX + 1) :
                if (dp[k - 1][j]) :
                    dp[k][j + arr[i]] = 1
  
    max_value = -1 * INF 
    min_value = INF
  
    for i in range(0, MAX * MAX + 1) :
  

1055
Chapter 148. Maximum and Minimum Values of an Algebraic Expression

        # 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
            temp = i - 50 * n
            max_value = max(max_value, 
                         temp * (sum - temp))
                                          
            min_value = min(min_value,
                         temp * (sum - temp))
      
    print ("Maximum Value: {}\nMinimum Value: {}"
                 .format(max_value, min_value))
  
# Driver Code
n = 2
m = 2
arr = [ 1, 2, 3, 4 ]
  
minMaxValues(arr, n, m) 
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// C# program to find the maximum


// and minimum values of an Algebraic
// expression of given form
using System;
using System.Collections.Generic;
  
class GFG {
      
    static double INF = 1e9;
    static int MAX = 50;
  
    static void minMaxValues(int []arr, int n, int m)
    {
          
        // Finding sum of array elements
        int sum = 0;
        for (int i = 0; i < (n + m); i++)

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

    // by choosing i numbers


    $dp = array();
      
    // new bool[MAX+1, MAX * MAX + 1];
    for($i = 0; $i < $MAX + 1; $i++)
    {
        for($j = 0; $j < $MAX * $MAX + 1; $j++)
            $dp[$i][$j] = 0; 
    }
      
    $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 ($i = 0; $i < ($n + $m); $i++) 
    {
  
        // k can be at max n because the
        // left expression has n numbers
        for ($k = min($n, $i + 1); 
                      $k >= 1; $k--) 
        {
            for ($j = 0; $j < $MAX * 
                              $MAX + 1; $j++)
            {
                if ($dp[$k - 1][$j])
                    $dp[$k][$j + $arr[$i]] = 1;
            }
        }
    }
  
    $max_value = -1 * $INF; 
    $min_value = $INF;
  
    for ($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 

1059
Chapter 148. Maximum and Minimum Values of an Algebraic Expression

            // indexing in array


            $temp = $i - 50 * $n;
            $max_value = max($max_value, $temp *
                                ($sum - $temp));
                                          
            $min_value = min($min_value, $temp * 
                                ($sum - $temp));
        }
    }
      
    echo ("Maximum Value: ". $max_value. "\n". 
          "Minimum Value: ". $min_value. "\n");
}
  
// Driver Code
$n = 2;
$m = 2;
$arr = [ 1, 2, 3, 4 ];
  
minMaxValues($arr, $n, $m); 
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

Output :

Maximum Value: 25
Minimum Value: 21

This approach will have a runtime complexity of O(MAX * MAX * (n+m)2 ).


Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/maximum-minimum-values-algebraic-expression/

1060
Chapter 149

Maximum and Minimum in a


square matrix.

Maximum and Minimum in a square matrix. - GeeksforGeeks


Given a square matrix of order n*n, find the maximum and minimum from the matrix given.
Examples:

Input : arr[][] = {5, 4, 9,


2, 0, 6,
3, 1, 8};
Output : Maximum = 9, Minimum = 0

Input : arr[][] = {-5, 3,


2, 4};
Output : Maximum = 4, Minimum = -5

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.

// C++ program for finding maximum and minimum in


// a matrix.
#include<bits/stdc++.h>
using namespace std;
  
#define MAX 100
  
// Finds maximum and minimum in arr[0..n-1][0..n-1]
// using pair wise comparisons
void maxMin(int arr[][MAX], int n)
{
    int min = INT_MAX;
    int max = INT_MIN;
  
    // Traverses rows one by one
    for (int i = 0; i < n; i++)
    {
        for (int 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])
                    min = arr[i][n-j-1];
                if (max< arr[i][j])
                    max = arr[i][j];
            }
            else
            {
                if (min > arr[i][j])
                    min = arr[i][j];
                if (max< arr[i][n-j-1])
                    max = arr[i][n-j-1];
            }
        }
    }
    cout << "Maximum = " << max;
         << ", Minimum = " << min;
}
  
/* Driver program to test above function */
int main()
{
    int arr[MAX][MAX] = {5, 9, 11,
                        25, 0, 14,
                        21, 6, 4};
    maxMin(arr, 3);

1062
Chapter 149. Maximum and Minimum in a square matrix.

    return 0;
}

Java

// Java program for finding maximum 


// and minimum in a matrix.
  
class GFG 
{
    static final int MAX = 100;
      
    // Finds maximum and minimum 
    // in arr[0..n-1][0..n-1]
    // using pair wise comparisons
    static void maxMin(int arr[][], int n)
    {
        int min = +2147483647;
        int max = -2147483648;
      
        // Traverses rows one by one
        for (int i = 0; i < n; i++)
        {
            for (int 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])
                        min = arr[i][n - j - 1];
                    if (max< arr[i][j])
                        max = arr[i][j];
                }
                else
                {
                    if (min > arr[i][j])
                        min = arr[i][j];
                    if (max< arr[i][n - j - 1])
                        max = arr[i][n - j - 1];
                }
            }
        }
        System.out.print("Maximum = "+max+
                         ", Minimum = "+min);
    }
      
    // Driver program 

1063
Chapter 149. Maximum and Minimum in a square matrix.

    public static void main (String[] args) 


    {
        int arr[][] = {{5, 9, 11},
                       {25, 0, 14},
                       {21, 6, 4}};
        maxMin(arr, 3);
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program for finding maximum 


// and minimum in a matrix.
using System;
  
public class GFG {
      
    // Finds maximum and minimum 
    // in arr[0..n-1][0..n-1]
    // using pair wise comparisons
    static void maxMin(int[,] arr, int n)
    {
        int min = +2147483647;
        int max = -2147483648;
      
        // Traverses rows one by one
        for (int i = 0; i < n; i++)
        {
            for (int 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])
                        min = arr[i,n - j - 1];
                    if (max < arr[i,j])
                        max = arr[i,j];
                }
                else
                {
                    if (min > arr[i,j])
                        min = arr[i,j];
                    if (max < arr[i,n - j - 1])
                        max = arr[i,n - j - 1];

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.

                    $min = $arr[$i][$n - $j - 1];


                if ($max< $arr[$i][$j])
                    $max = $arr[$i][$j];
            }
            else
            {
                if ($min > $arr[$i][$j])
                    $min = $arr[$i][$j];
                if ($max < $arr[$i][$n - $j - 1])
                    $max = $arr[$i][$n - $j - 1];
            }
        }
    }
    echo "Maximum = " , $max
        ,", Minimum = " , $min;
}
  
    // Driver Code
    $arr = array(array(5, 9, 11),
                array(25, 0, 14),
                array(21, 6, 4));
    maxMin($arr, 3);
      
// This code is contributed by anuj_67.
?>

Output:

Maximum = 25, Minimum = 0

Improved By : shrikanth13, vt_m

Source

https://www.geeksforgeeks.org/maximum-and-minimum-in-a-square-matrix/

1066
Chapter 150

Maximum decimal value path in


a binary matrix

Maximum decimal value path in a binary matrix - GeeksforGeeks


Given binary square matrix [n*n]. Find maximum integer value in a path from top left to
bottom right. We compute integer value using bits of traversed path. We start at index
[0,0] and end at index [n-1][n-1]. from index [i, j], we can move [i, j+1] or [i+1, j].
Examples:

Input : mat[][] = {{1, 1, 0, 1},


{0, 1, 1, 0},
{1, 0, 0, 1},
{1, 0, 1, 1}}
Output : 111
Explanation :
Path : (0,0) -> (0,1) -> (1,1) -> (1,2) ->
(2,2) -> (3,2) ->(4,4)
Decimal value : 1*(2^0) + 1*(2^1) + 1*(2^2) + 1*(2^3) +
0*(2^4) + 1*(2^5) + 1*(2^6) = 111

The above problem can be recursively defined as below:

// p indicates power of 2, initially p = i = j = 0


MaxDecimalValue(mat, i, j, p)

// If i or j is our of boundary
If i >= n || j >= n
return 0

1067
Chapter 150. Maximum decimal value path in a binary matrix

// Compute rest of matrix find maximum decimal value


result max(MaxDecimalValue(mat, i, j+1, p+1),
MaxDecimalValue(mat, i+1, j, p+1))

If mat[i][j] == 1
return power(2, p) + result
Else
return result

Below is the implementation of above recursive algorithm.


C++

    
// C++ program to find maximum decimal value path in
// binary matrix
#include<bits/stdc++.h>
using namespace std;
  
#define N 4
  
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
long long int maxDecimalValue(int mat[][N], int i, int j,
                                                   int p)
{
    // Out of matrix boundary
    if (i >= N || j >= N )
        return 0;
  
    int result = max(maxDecimalValue(mat, i, j+1, p+1),
                     maxDecimalValue(mat, i+1, j, p+1));
  
    // If current matrix value is 1 then return result +
    // power(2, p) else result
    if (mat[i][j] == 1)
        return pow(2, p) + result;
    else
        return result;
}
  
//Driver program
int main()
{
    int mat[][4] = {{ 1 ,1 ,0 ,1 },
        { 0 ,1 ,1 ,0 },
        { 1 ,0 ,0 ,1 },

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

# Python program to find maximum decimal


# value path in binary matrix
N =4
  
# Returns maximum decimal value in binary
# matrix. Here p indicate power of 2
def maxDecimalValue(mat, i, j, p):
  
    # Out of matrix boundary
    if i >= N or j >= N:
        return 0
          
    result = max(
        maxDecimalValue(mat, i, j+1, p+1),
        maxDecimalValue(mat, i+1, j, p+1))
  
    # If current matrix value is 1 then
    # return result + power(2, p) else
    # result
    if mat[i][j] == 1:
        return pow(2, p) + result
    else:
        return result
  
  
# Driver Program
mat = [ [1, 1, 0, 1],
        [0, 1, 1, 0],
        [1, 0, 0, 1],
        [1, 0, 1, 1] ]
  
print(maxDecimalValue(mat, 0, 0, 0))
  
# This code is contributed by Shrikant13.

PHP

<?php

1069
Chapter 150. Maximum decimal value path in a binary matrix

// PHP program to find maximum 


// decimal value path in binary
// matrix
  
// Returns maximum decimal value
// in binary matrix. Here p 
// indicate power of 2
function maxDecimalValue($mat, $i, 
                          $j, $p)
{
    $N=4;
      
    // Out of matrix boundary
    if ($i >= $N || $j >= $N )
        return 0;
  
    $result = max(maxDecimalValue($mat, $i, 
                            $j + 1, $p + 1),
                  maxDecimalValue($mat, $i + 1,
                                $j, $p + 1));
  
    // If current matrix value 
    // is 1 then return result +
    // power(2, p) else result
    if ($mat[$i][$j] == 1)
        return pow(2, $p) + $result;
    else
        return $result;
}
  
    // Driver Code
    $mat = array(array(1 ,1 ,0 ,1),
                 array(0 ,1 ,1 ,0),
                 array(1 ,0 ,0 ,1),
                 array(1 ,0 ,1 ,1));
  
    echo maxDecimalValue($mat, 0, 0, 0) ;
      
// This code is contributed by nitin mittal. 
?>

Output:

111

The time complexity of above recursive solution is exponential.

1070
Chapter 150. Maximum decimal value path in a binary matrix

Here matrix [3][3]


(2 2)
/ \
(1 2) (2 1)
/ \ / \
(0 2) (1 1) (1 1) (2 1)
/ \ / \ / \ / \
. . . . . . . .
. . . . . . . . and so no

If we see recursion tree of above recursive solution, we can observe overlapping sub-problems.
Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic
Programming. Below is Dynamic Programming based solution.
Below is c++ implementation of above problem using Dynamic Programming

// C++ program to find Maximum decimal value Path in


// Binary matrix
#include<bits/stdc++.h>
using namespace std;
#define N 4
  
// Returns maximum decimal value in binary matrix.
// Here p indicate power of 2
long long int MaximumDecimalValue(int mat[][N], int n)
{
    int dp[n][n];
    memset(dp, 0, sizeof(dp));
    if (mat[0][0] == 1)
        dp[0][0] = 1 ; // 1*(2^0)
  
    // Compute binary stream of first row of matrix
    // and store result in dp[0][i]
    for (int i=1; i<n; i++)
    {
        // indicate 1*(2^i) + result of previous
        if (mat[0][i] == 1)
            dp[0][i] = dp[0][i-1] + pow(2, i);
  
        // indicate 0*(2^i) + result of previous
        else
            dp[0][i] = dp[0][i-1];
    }
  
    // Compute binary stream of first column of matrix
    // and store result in dp[i][0]
    for (int i = 1 ; i <n ; i++ )

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

Time Complexity : O(n2 )

1072
Chapter 150. Maximum decimal value path in a binary matrix

Auxiliary space : O(n2 )


Improved By : shrikanth13, nitin mittal

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

Maximum determinant of a matrix with every values either 0 or n - GeeksforGeeks


We have given a positive number n, and we have to find a 3*3 matrix which can be formed
with combination of 0 or n and has maximum determinant.
Examples :

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++

// C++ program to find  maximum possible determinant


// of 0/n matrix.
#include <bits/stdc++.h>
using namespace std;
  
// Function for maximum determinant
int maxDet(int n)
{
    return (2*n*n*n);
}
  
// Function to print resulatant matrix
void resMatrix ( int n)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            // three position where 0 appears
            if (i == 0 && j == 2)
                cout << "0 ";
            else if (i == 1 && j == 0)
                cout << "0 ";
            else if (i == 2 && j == 1)
                cout << "0 ";
  
            // position where n appears
            else
                cout << n << " ";
        }
        cout << "\n";
    }

  
// Driver code
int main()
{
    int n = 15;
    cout << "Maximum Determinant = " << maxDet(n);
  
    cout << "\nResultant Matrix :\n";
    resMatrix(n); 
  
    return 0;
}

1075
Chapter 151. Maximum determinant of a matrix with every values either 0 or n

Java

// Java program to find maximum possible


// determinant of 0/n matrix.
import java.io.*;
  
public class GFG
{
      
// Function for maximum determinant
static int maxDet(int n)
{
    return (2 * n * n * n);
}
  
  
// Function to print resulatant matrix
void resMatrix(int n)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            // three position where 0 appears
            if (i == 0 && j == 2)
                System.out.print("0 ");
            else if (i == 1 && j == 0)
                System.out.print("0 ");
            else if (i == 2 && j == 1)
                System.out.print("0 ");
  
            // position where n appears
            else
                System.out.print(n +" ");
        }
        System.out.println("");
    }

  
    // Driver code
    static public void main (String[] args)
    {
            int n = 15;
            GFG geeks=new GFG();
            System.out.println("Maximum Determinant = "
                                + maxDet(n));
  
            System.out.println("Resultant Matrix :"); 

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#

// C# program to find maximum possible


// determinant of 0/n matrix.
using System;
  
public class GFG
{
      
// Function for maximum determinant
static int maxDet(int n)
{
    return (2 * n * n * n);
}
  
  
// Function to print resulatant matrix
void resMatrix(int n)
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            // three position where 0 appears
            if (i == 0 && j == 2)
                Console.Write("0 ");
            else if (i == 1 && j == 0)
                Console.Write("0 ");
            else if (i == 2 && j == 1)
                Console.Write("0 ");
  
            // position where n appears
            else
                Console.Write(n +" ");
        }
        Console.WriteLine("");
    }

  
    // Driver code
    static public void Main (String []args)

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 :

Maximum Determinant = 6750


Resultant Matrix :
15 15 0
0 15 15
15 0 15

Exercise: Extend the above solution for a generalized k x k matrix.


Improved By : vt_m, nitin mittal

Source

https://www.geeksforgeeks.org/maximum-determinant-matrix-every-values-either-0-n/

1079
Chapter 152

Maximum difference of sum of


elements in two rows in a matrix

Maximum difference of sum of elements in two rows in a matrix - GeeksforGeeks


Given a matrix of m*n order, the task is to find the maximum difference between two rows
Rj and Ri such that i < j, i.e., we need to find maximum value of sum(Rj) – sum(Ri) such
that row i is above row j.
Examples:

Input : mat[5][4] = {{-1, 2, 3, 4},


{5, 3, -2, 1},
{6, 7, 2, -3},
{2, 9, 1, 4},
{2, 1, -2, 0}}
Output: 9
// difference of R3 - R1 is maximum

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

// C++ program to find maximum difference of sum of


// elements of two rows
#include<bits/stdc++.h>
#define MAX 100
using namespace std;
  
// Function to find maximum difference of sum of
// elements of two rows such that second row appears
// before first row.
int maxRowDiff(int mat[][MAX], int m, int n)
{
    // auxiliary array to store sum of all elements
    // of each row
    int rowSum[m];
  
    // calculate sum of each row and store it in
    // rowSum array
    for (int i=0; i<m; i++)
    {
        int sum = 0;
        for (int j=0; j<n; j++)
            sum += mat[i][j];
        rowSum[i] = sum;
    }
  
    // calculating maximum difference of two elements
    // such that rowSum[i]<rowsum[j]
    int max_diff = rowSum[1] - rowSum[0];
    int min_element = rowSum[0];
    for (int 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 program to run the case
int main()

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

// Java program to find maximum difference


// of sum of elements of two rows
class GFG {
static final int MAX = 100;
  
// Function to find maximum difference of sum 
// of elements of two rows such that second 
// row appears before first row.
static int maxRowDiff(int mat[][], int m, int n) {
  
    // auxiliary array to store sum 
    // of all elements of each row
    int rowSum[] = new int[m];
  
    // calculate sum of each row and 
    // store it in rowSum array
    for (int i = 0; i < m; i++) {
    int sum = 0;
    for (int j = 0; j < n; j++)
        sum += mat[i][j];
    rowSum[i] = sum;
    }
  
    // calculating maximum difference of two elements
    // such that rowSum[i]<rowsum[j]
    int max_diff = rowSum[1] - rowSum[0];
    int min_element = rowSum[0];
    for (int 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;
  

1082
Chapter 152. Maximum difference of sum of elements in two rows in a matrix

    // 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
public static void main(String[] args) {
    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}};
  
    System.out.print(maxRowDiff(mat, m, n));
}
}
// This code is contributed by Anant Agarwal.

Python3

# Python3 program to find maximum difference 


# of sum of elements of two rows
  
# Function to find maximum difference of 
# sum of elements of two rows such that 
# second row appears before first row.
def maxRowDiff(mat, m, n):
      
    # auxiliary array to store sum of 
    # all elements of each row
    rowSum = [0] * m
      
    # calculate sum of each row and 
    # store it in rowSum array
    for i in range(0, m):
        sum = 0
        for j in range(0, n):
            sum += mat[i][j] 
        rowSum[i] = sum
      
    # calculating maximum difference of 
    # two elements such that 

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#

// C# program to find maximum difference


// of sum of elements of two rows
using System;
  
class GFG {
      
    // Function to find maximum difference 
    // of sum of elements of two rows such
    // that second row appears before
    // first row.
    static int maxRowDiff(int [,] mat, 
                              int m, int n)
    {
      

1084
Chapter 152. Maximum difference of sum of elements in two rows in a matrix

        // auxiliary array to store sum 


        // of all elements of each row
        int [] rowSum = new int[m];
      
        // calculate sum of each row and 
        // store it in rowSum array
        for (int i = 0; i < m; i++)
        {
            int sum = 0;
              
            for (int j = 0; j < n; j++)
                sum += mat[i,j];
                  
            rowSum[i] = sum;
        }
      
        // calculating maximum difference
        // of two elements such that 
        // rowSum[i] < rowsum[j]
        int max_diff = rowSum[1] - rowSum[0];
        int min_element = rowSum[0];
          
        for (int 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
    public static void Main()
    {

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:

Time complexity : O(m*n)


Auxiliary space : O(m)
Improved By : KRV, jit_t

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

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:

Output for above example is 2.

In above diagram, mirror at (3, 1) and (5, 5) are able


to send light from bottom to right so total possible
mirror count is 2.

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.

// C++ program to find how many mirror can transfer


// light from bottom to right
#include <bits/stdc++.h>
using namespace std;
  
// method returns number of mirror which can transfer
// light from bottom to right
int maximumMirrorInMatrix(string mat[], int N)
{
    // To store first obstacles horizontaly (from right)
    // and vertically (from bottom)
    int horizontal[N], vertical[N];
  
    // initialize both array as -1, signifying no obstacle
    memset(horizontal, -1, sizeof(horizontal));
    memset(vertical, -1, sizeof(vertical));
  
    // looping matrix to mark column for obstacles
    for (int i=0; i<N; i++)
    {
        for (int j=N-1; j>=0; j--)
        {
            if (mat[i][j] == 'B')
                continue;
  
            // mark rightmost column with obstacle
            horizontal[i] = j;
            break;
        }
    }
  
    // looping matrix to mark rows for obstacles
    for (int j=0; j<N; j++)
    {
        for (int i=N-1; i>=0; i--)
        {
            if (mat[i][j] == 'B')
                continue;
  
            // mark leftmost row with obstacle
            vertical[j] = i;
            break;
        }
    }

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

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:

// CPP program to find maximum number 


// of customers that can be satisfied
#include <bits/stdc++.h>
using namespace std;
  
vector<pair<long long, int> > v;
  

1094
Chapter 154. Maximum number of customers that can be satisfied with given quantity

// print maximum number of satisfied


// customers and their indexes 
void solve(int n, int d, int a, int b, 
                        int arr[][2])
{
    // Creating an vector of pair of 
    // total demand and customer number
    for (int i = 0; i < n; i++) {
        int m = arr[i][0], t = arr[i][1];
        v.push_back(make_pair((a * m + b * t),
                                     i + 1));
    }
      
    // Sorting the customers according
    // to their total demand
    sort(v.begin(), v.end());
      
    vector<int> ans;
      
    // Taking the first k customers that
    // can be satisfied by total amount d
    for (int i = 0; i < n; i++) {
        if (v[i].first <= d) {
            ans.push_back(v[i].second);
            d -= v[i].first;
        }
    }
      
    cout << ans.size() << endl;    
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i] << " ";
}
  
// Driver program
int main()
{
    // Initializing variables
    int n = 5;
    long d = 5;
    int a = 1, b = 1;
    int arr[][2] = {{2, 0},
                    {3, 2},
                    {4, 4},
                    {10, 0},
                    {0, 1}};
      
    solve(n, d, a, b, arr);
    return 0;

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

Maximum number of ones in a


N*N matrix with given
constraints

Maximum number of ones in a N*N matrix with given constraints - GeeksforGeeks

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

total number of cells available is in a NxN matrix.

Below is the implementation of the above approach:


C++

// C++ program to get Maximum Number of


// ones in a matrix with given constraints
#include <bits/stdc++.h>
  
using namespace std;
  
// Function that returns the maximum 
// number  of ones 
int getMaxOnes(int n, int x)
{
    // Minimum number of zeroes
    int zeroes = (n / x);
    zeroes = zeroes * zeroes;
  
    // Totol cells = square of the size of the matrices
    int total = n * n;
  
    // Intialising the answer
    int ans =  total - zeroes;
  
    return ans; 
}
  
// Driver code
int main()
{
    // Intitalising the variables
    int n = 5;
    int x = 2;
  
      
    cout << getMaxOnes(n, x);
  
    return 0;

1098
Chapter 155. Maximum number of ones in a N*N matrix with given constraints

Java

// Java program to get Maximum


// Number of ones in a matrix 
// with given constraints
import java.io.*;
  
class GFG
{
      
// Function that returns 
// the maximum number of ones 
static int getMaxOnes(int n, 
                      int x)
{
    // Minimum number of zeroes
    int zeroes = (n / x);
    zeroes = zeroes * zeroes;
  
    // Totol cells = square of
    // the size of the matrices
    int total = n * n;
  
    // Intialising the answer
    int ans = total - zeroes;
  
    return ans; 
}
  
// Driver code
public static void main (String[] args) 
{
  
// Intitalising the variables
int n = 5;
int x = 2;
System.out.println(getMaxOnes(n, x));
}
}
  
// This code is contributed
// by akt_mit

Python3

# Python3 program to get 

1099
Chapter 155. Maximum number of ones in a N*N matrix with given constraints

# Maximum Number of ones 


# in a matrix with given
# constraints
  
# Function that returns 
# the maximum number of ones 
def getMaxOnes(n, x):
      
    # Minimum number
    # of zeroes
    zeroes = (int)(n / x);
    zeroes = zeroes * zeroes;
  
    # Totol cells = square of
    # the size of the matrices
    total = n * n;
  
    # Intialising 
    # the answer
    ans = total - zeroes;
  
    return ans; 
  
# Driver code
  
# Intitalising the variables
n = 5;
x = 2;
print(getMaxOnes(n, x));
  
# This code is contributed
# by mits

C#

// C# program to get Maximum


// Number of ones in a matrix 
// with given constraints
using System;
  
class GFG
{
      
// Function that returns 
// the maximum number of ones 
static int getMaxOnes(int n, 
                      int x)
{

1100
Chapter 155. Maximum number of ones in a N*N matrix with given constraints

    // Minimum number of zeroes


    int zeroes = (n / x);
    zeroes = zeroes * zeroes;
  
    // Totol cells = square of
    // the size of the matrices
    int total = n * n;
  
    // Intialising the answer
    int ans = total - zeroes;
  
    return ans; 
}
  
// Driver code
static public void Main ()
{
          
    // Intitalising the
    // variables
    int n = 5;
    int x = 2;
    Console.WriteLine(getMaxOnes(n, x));
}
}
  
// This code is contributed
// by ajit

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

Time Complexity: O(1)


Auxiliary Space: O(1)
Improved By : jit_t, Mithun Kumar

Source

https://www.geeksforgeeks.org/maximum-number-of-ones-in-a-nn-matrix-with-given-constraints/

1102
Chapter 156

Maximum path sum in matrix

Maximum path sum in matrix - GeeksforGeeks


Given a matrix of N * M. Find the maximum path sum in matrix. The maximum path is
sum of all elements from first row to last row where you are allowed to move only down or
diagonally to left or right. You can start from any element in first row.
Examples:

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++

// CPP prorgam for finding max path in matrix


#include <bits/stdc++.h>
#define N 4
#define M 6

1103
Chapter 156. Maximum path sum in matrix

using namespace std;


  
// To calculate max path in matrix
int findMaxPath(int mat[][M])
{
  
    for (int i = 1; i < N; i++) {
        for (int j = 0; j < M; j++) {
  
            // When all paths are possible
            if (j > 0 && j < M - 1)
                mat[i][j] += max(mat[i - 1][j],
                             max(mat[i - 1][j - 1], 
                             mat[i - 1][j + 1]));
  
            // When diagonal right is not possible
            else if (j > 0)
                mat[i][j] += max(mat[i - 1][j],
                            mat[i - 1][j - 1]);
  
            // When diagonal left is not possible
            else if (j < M - 1)
                mat[i][j] += max(mat[i - 1][j],
                            mat[i - 1][j + 1]);
  
            // Store max path sum
        }
    }
    int res = 0;
    for (int j = 0; j < M; j++) 
        res = max(mat[N-1][j], res);
    return res;
}
  
// Driver program to check findMaxPath
int main()
{
      
    int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 },
                    { 1, 0, 0, 30, 2, 5 },
                    { 0, 10, 4, 0, 2, 0 },
                    { 1, 0, 2, 20, 0, 4 } };
              
    cout << findMaxPath(mat1) << endl;
    return 0;
}

Java

1104
Chapter 156. Maximum path sum in matrix

// Java prorgam for finding max path in matrix


  
import static java.lang.Math.max;
  
class GFG 
{
    public static int N = 4, M = 6;
      
    // Function to calculate max path in matrix
    static int findMaxPath(int mat[][])
    {
        // To find max val in first row
        int res = -1;
        for (int i = 0; i < M; i++)
            res = max(res, mat[0][i]);
  
        for (int i = 1; i < N; i++) 
        {
            res = -1;
            for (int j = 0; j < M; j++) 
            {
                // When all paths are possible
                if (j > 0 && j < M - 1)
                    mat[i][j] += max(mat[i - 1][j],
                                 max(mat[i - 1][j - 1], 
                                    mat[i - 1][j + 1]));
  
                // When diagonal right is not possible
                else if (j > 0)
                    mat[i][j] += max(mat[i - 1][j],
                                    mat[i - 1][j - 1]);
  
                // When diagonal left is not possible
                else if (j < M - 1)
                    mat[i][j] += max(mat[i - 1][j],
                                mat[i - 1][j + 1]);
  
                // Store max path sum
                res = max(mat[i][j], res);
            }
        }
        return res;
    }
      
    // driver program
    public static void main (String[] args) 
    {
        int mat[][] = { { 10, 10, 2, 0, 20, 4 },

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

# Python 3 prorgam for finding max path in matrix


# To calculate max path in matrix
  
def findMaxPath(mat):
  
    # To find max val in first row
    res = -1
    for i in range(M):
        res = max(res, mat[0][i])
   
    for i in range(1, N):
   
        res = -1
        for j in range(M):
   
            # When all paths are possible
            if (j > 0 and j < M - 1):
                mat[i][j] += max(mat[i - 1][j],
                                 max(mat[i - 1][j - 1], 
                                     mat[i - 1][j + 1]))
   
            # When diagonal right is not possible
            elif (j > 0):
                mat[i][j] += max(mat[i - 1][j],
                                 mat[i - 1][j - 1])
   
            # When diagonal left is not possible
            elif (j < M - 1):
                mat[i][j] += max(mat[i - 1][j],
                                 mat[i - 1][j + 1])
   
            # Store max path sum
            res = max(mat[i][j], res)
    return res
  

1106
Chapter 156. Maximum path sum in matrix

# Driver program to check findMaxPath


N=4
M=6
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 ]])
                
print(findMaxPath(mat))
  
# This code is contributed by Azkia Anam.

C#

// C# prorgam for finding


// max path in matrix
using System;
  
class GFG 
{
    static int N = 4, M = 6;
      
    // find the max element
    static int max(int a, int b)
    {
        if(a > b)
        return a;
        else
        return b;
    }
      
    // Function to calculate
    // max path in matrix
    static int findMaxPath(int [,]mat)
    {
        // To find max val 
        // in first row
        int res = -1;
        for (int i = 0; i < M; i++)
            res = max(res, mat[0, i]);
  
        for (int i = 1; i < N; i++) 
        {
            res = -1;
            for (int j = 0; j < M; j++) 
            {
                // When all paths are possible
                if (j > 0 && j < M - 1)

1107
Chapter 156. Maximum path sum in matrix

                    mat[i, j] += max(mat[i - 1, j],


                                 max(mat[i - 1, j - 1], 
                                     mat[i - 1, j + 1]));
  
                // When diagonal right
                // is not possible
                else if (j > 0)
                    mat[i, j] += max(mat[i - 1, j],
                                     mat[i - 1, j - 1]);
  
                // When diagonal left 
                // is not possible
                else if (j < M - 1)
                    mat[i, j] += max(mat[i - 1, j],
                                 mat[i - 1, j + 1]);
  
                // Store max path sum
                res = max(mat[i, j], res);
            }
        }
        return res;
    }
      
    // Driver code
    static public void Main (String[] args) 
    {
        int[,] 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}};
  
        Console.WriteLine(findMaxPath(mat));
    }
}
  
// This code is contributed 
// by Arnab Kundu

Output:

74

Time Complexity: O(N*M)


Improved By : andrew1234

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

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:

Input : mat[4][4] = { {4, 2, 3, 4},


{2, 9, 1, 10},
{15, 1, 3, 0},
{16, 92, 41, 44} };
Output :120
path : 4 + 9 + 15 + 92 = 120

Asked in: Amazon interview

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

The above problem can be recursively defined.


Let initial position be MaximumPathSum(N-1, j), where j varies from 0 to N-1. We return
maximum value between all path that we start traversing (N-1, j) [ where j varies from 0 to
N-1]

i = N-1, j = 0 to N -1
int MaximumPath(Mat[][N], I, j)

// IF we reached to first row of


// matrix then return value of that
// element
IF ( i == 0 && j = 0 )
return Mat[i][j]

// out of matrix bound


IF( i = N || j < 0 )
return 0;

// call all rest position that we reached


// from current position and find maximum
// between them and add current value in
// that path
return max(MaximumPath(Mat, i-1, j),
MaximumPath(Mat, i-1, j-1),
MaximumPath(Mat, i-1, j+1)))
+ Mat[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

// C++ program to find Maximum path sum


// start any column in row '0' and ends
// up to any column in row 'n-1'
#include<bits/stdc++.h>
using namespace std;
#define N 4
  
// function find maximum sum path
int MaximumPath(int Mat[][N])
{
    int result = 0 ;
  

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

    // creat 2D matrix to store the sum


    // of the path
    int dp[N][N+2];
  
    // initialize all dp matrix as '0'
    memset(dp, 0, sizeof(dp));
  
    // 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] = max(dp[i-1][j-1],
                           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 = max(result, dp[N-1][i]);
  
    // return maximum sum path
    return result ;
}
  
// driver program to test above function
int main()
{
    int Mat[4][4] = { { 4, 2 , 3 , 4 },
        { 2 , 9 , 1 , 10},
        { 15, 1 , 3 , 0 },
        { 16 ,92, 41, 44 }
    };
  
    cout << MaximumPath ( Mat ) <<endl ;
    return 0;
}

Java

// Java program to find Maximum path sum


// start any column in row '0' and ends
// up to any column in row 'n-1'
import java.util.*;
  

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

# Python program to find


# Maximum path sum
# start any column in
# row '0' and ends
# up to any column in row 'n-1'
  
N = 4
  
# function find maximum sum path
def MaximumPath(Mat):
  
    result = 0
  
    # create 2D matrix to store the sum
    # of the path
    # initialize all dp matrix as '0'
    dp = [[0 for i in range(N+2)] for j in range(N)]
  
    # copy all element of first column into
    # dp first column
    for i in range(N):
        for j in range(1, N+1):
            dp[i][j] = max(dp[i-1][j-1],
                           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 i in range(N+1):
        result = max(result, dp[N-1][i])
  
    # return maximum sum path
    return result
  
# driver program to test above function
Mat = [[4, 2, 3, 4],
       [2, 9, 1, 10],
       [15, 1, 3, 0],
       [16, 92, 41, 44]]
  
print(MaximumPath(Mat))

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

Time complexity : O(N2 )

Source

https://www.geeksforgeeks.org/maximum-path-sum-starting-cell-0-th-row-ending-cell-n-1-th-row/

1115
Chapter 158

Maximum points collected by


two persons allowed to meet
once

Maximum points collected by two persons allowed to meet once - GeeksforGeeks


Given a 2-D matrix A[N][M] where A[i][j] denotes the points available on this cell. Two
persons, P1 and P2, start from two corners of this matrix. P1 starts from top left and needs
to reach bottom right. On the other hand, P2 starts bottom left and needs to reach top
right. P1 can move right and down. P2 can right and up. As they visit a cell, points A[i][j]
are added to their total. The task is to maximize the sum of total points collected by both
of them under the condition that they shall meet only once and the cost of this cell shall
not be included in either of their total.
Examples:

Input : A[][] = { {100, 100, 100},


{100, 1, 100},
{100, 100, 100}};
Output : 800
P1 needs to go from (0,0) to (2,2)
P2 needs to go from (2,0) to (0,2)
Explanation: P1 goes through A[0][0]->A[0][1]->A[1][1]->
A[2][1]->A[2][2].
P2 goes through A[2][0]->A[1][0]->A[1][1]->
A[1][2]->A[0][2].
They meet at A[2][2]. So total points collected:
A[0][0] + A[0][1] + A[2][1] + A[2][2] +
A[2][0] + A[1][0] + A[1][2] + A[0][2] = 800

1116
Chapter 158. Maximum points collected by two persons allowed to meet once

Input : A[][] = {{100, 100, 100, 100},


{100, 100, 100, 100},
{100, 0, 100, 100},
{100, 100, 100, 100}};
Output : 1200

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.

// C++ program to find maximum points that can


// be collected by two persons in a matrix.
#include<bits/stdc++.h>
#define M 3
#define N 3
using namespace std;
  
int findMaxPoints(int A[][M])
{
    // To store points collected by Person P1
    // when he/she begins journy from start and
    // from end.
    int P1S[M+1][N+1], P1E[M+1][N+1];
    memset(P1S, 0, sizeof(P1S));
    memset(P1E, 0, sizeof(P1E));
  
    // To store points collected by Person P2

1117
Chapter 158. Maximum points collected by two persons allowed to meet once

    // when he/she begins journey from start and


    // from end.
    int P2S[M+1][N+1], P2E[M+1][N+1];
    memset(P2S, 0, sizeof(P2S));
    memset(P2E, 0, sizeof(P2E));
  
    // Table for P1's journey from
    // start to meeting cell
    for (int i=1; i<=N; i++)
        for (int j=1; j<=M; j++)
            P1S[i][j] = max(P1S[i-1][j],
                  P1S[i][j-1]) + A[i-1][j-1];
  
    // Table for P1's journey from
    // end to meet cell
    for (int i=N; i>=1; i--)
        for (int j=M; j>=1; j--)
            P1E[i][j] = max(P1E[i+1][j],
                  P1E[i][j+1]) + A[i-1][j-1];
  
    // Table for P2's journey from start to meeting cell
    for (int i=N; i>=1; i--)
        for(int j=1; j<=M; j++)
            P2S[i][j] = max(P2S[i+1][j],
                  P2S[i][j-1]) + A[i-1][j-1];
  
    // Table for P2's journey from end to meeting cell
    for (int i=1; i<=N; i++)
        for (int j=M; j>=1; j--)
            P2E[i][j] = max(P2E[i-1][j],
                  P2E[i][j+1]) + A[i-1][j-1];
  
    // Now iterate over all meeting positions (i,j)
    int ans = 0;
    for (int i=2; i<N; i++)
    {
        for (int j=2; j<M; j++)
        {
            int op1 = P1S[i][j-1] + P1E[i][j+1] +
                      P2S[i+1][j] + P2E[i-1][j];
            int op2 = P1S[i-1][j] + P1E[i+1][j] +
                      P2S[i][j-1] + P2E[i][j+1];
            ans = max(ans, max(op1, op2));
        }
    }
    return ans;
}
  

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:

Max Points : 800

Time Complexity : O(N * M)


Auxiliary Space : O(N * M)

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

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:

If we consider as two independent path, then

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

There are 4 * on each path. Hence, total = 8.


Thus we see that the optimal solution is not the sum of optimal solutions of both the path
independently. The optimal answer for one does not ensure an optimal answer.
So, we will have to calculate both the paths simultaneously. This is needed because the
answer for path 2 depends on the route chosen by path 1. Simultaneous calculation can be
done by considering two path from (0, 0) to (N-1, M-1) and making four decisions at each
position (two for each).
So instead of two traveling one path from top left to bottom right and other from bottom
right to top left, we will travel two path from (0, 0) to (N-1, M-1) simultaneously, so at each
step we take one step for both path. So our state will consist of (x1, y1, x2, y2) where (x1,
y1) is position of first path and (x2, y2) is position of second tourist in grid.
Points to notice:
1. At each step either step can move right or down, so we have 4 choices for movement(2
choice for each path).
2. If both path are on the same cell (x1 == x2 and y1 == y2) then we can add only 1 to
result if that cell have *.
3. We can reduce the complexity by reducing state dimesion from 4 to 3. If we know the
position of first path (x1, y1) the x coordinate of second path x2, then we must have x1 +
y1 = x2 + y2 since both path cover the same distance in same amount of time. So y2 = x1
+ y1 – x2 and our state depends only on (x1, y1, x2).
Below is C++ implementation of this approach:

// CPP program to find maximum points that can 


// be collected in a journey from top to bottom 
// and then back from bottom to top,
#include <bits/stdc++.h>
#define MAX 5
#define N 5

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

        row2 >= n || col2 >= m)


        return -1 * inf;
  
    // If already calculated, return the value
    if (dp[row1][col1][row2] != -1)
        return dp[row1][col1][row2];
  
    // Vaiable for 4 options.
    int ch1 = -1 * inf, ch2 = -1 * inf;
    int ch3 = -1 * inf, ch4 = -1 * inf;
  
    // If path 1 is moving right and path 2 
    // is moving down.
    if (grid[row1][col1 + 1] != '#' && 
        grid[row2 + 1][col2] != '#')
      ch1 = cost(grid, row1, col1 + 1, row2 + 1, col2) + 
        solve(n, m, grid, dp, row1, col1 + 1, row2 + 1);
  
    // If path 1 is moving right and path 2 is moving
    // right.
    if (grid[row1][col1 + 1] != '#' && 
        grid[row2][col2 + 1] != '#')
      ch2 = cost(grid, row1, col1 + 1, row2, col2 + 1) + 
            solve(n, m, grid, dp, row1, col1 + 1, row2);
  
    // If path 1 is moving down and path 2 is moving right.
    if (grid[row1 + 1][col1] != '#' && 
        grid[row2][col2 + 1] != '#')
     ch3 = cost(grid, row1 + 1, col1, row2, col2 + 1) + 
           solve(n, m, grid, dp, row1 + 1, col1, row2);
  
    // If path 1 is moving down and path 2 is moving down.
    if (grid[row1 + 1][col1] != '#' && 
        grid[row2 + 1][col2] != '#')
      ch4 = cost(grid, row1 + 1, col1, row2 + 1, col2) +
         solve(n, m, grid, dp, row1 + 1, col1, row2 + 1);
  
    // Returning the maximum of 4 options.
    return dp[row1][col1][row2] = max({ch1, ch2, ch3, ch4});
}
  
// Wrapper Function
int wrapper(int n, int m, char grid[N][M])
{
    int ans = 0;
    int dp[MAX][MAX][MAX];
    memset(dp, -1, sizeof dp);
  

1124
Chapter 159. Maximum points from top left of matrix to bottom right and return back

    // If last bottom right cell is blcoked


    if (grid[n - 1][m - 1] == '#' || grid[0][0] == '#')
        ans = -1 * inf;
  
    // If top left cell contain *
    if (grid[0][0] == '*')
        ans++;
    grid[0][0] = '.';
  
    // If bottom right cell contain *
    if (grid[n - 1][m - 1] == '*')
        ans++;
    grid[n - 1][m - 1] = '.';
  
    ans += solve(n, m, grid, dp, 0, 0, 0);
    return max(ans, 0);
}
  
// Driven Program
int main()
{
    int n = 5, m = 5;
  
    char grid[N][M] = {
        { '.', '*', '.', '*', '.' },
        { '*', '#', '#', '#', '.' },
        { '*', '.', '*', '.', '*' },
        { '.', '#', '#', '#', '*' },
        { '.', '*', '.', '*', '.' }
    };
  
    cout << wrapper(n, m, grid) << endl;
    return 0;
}

Output:

Time Complexity: O(N^3)

Source

https://www.geeksforgeeks.org/maximum-points-top-left-matrix-bottom-right-return-back/

1125
Chapter 160

Maximum product of 4 adjacent


elements in matrix

Maximum product of 4 adjacent elements in matrix - GeeksforGeeks


Given a square matrix, find the maximum product of four adjacent elements of matrix. The
adjacent elements of matrix can be top, down, left, right, diagonal or anti diagonal. The
four or more numbers should be adjacent to each other.
Note: n should be greater than or equal to 4 i.e n >= 4
Examples :

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++

// C++ program to find out the maximum product


// in the matrix which four elements are 
// adjacent to each other in one direction
#include <bits/stdc++.h>
using namespace std;
  
const int n = 5;
  
// function to find max product
int FindMaxProduct(int arr[][n], int n)
{
    int max = 0, result;
  
    // iterate the rows.
    for (int i = 0; i < n; i++) 
    {
  
        // iterate the columns.
        for (int j = 0; j < n; j++) 
        {
  
            // check the maximum product 
            // in horizontal row.
            if ((j - 3) >= 0) 

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

// Java program to find out the


// maximum product in the matrix
// which four elements are adjacent
// to each other in one direction
class GFG 
{
static final int n = 5;
  
// function to find max product
static int FindMaxProduct(int arr[][], int n) 
{
    int max = 0, result;
  
    // iterate the rows.
    for (int i = 0; i < n; i++) 
    {
    // iterate the columns.
    for (int j = 0; j < n; j++) 
    {
        // 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];

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

// C# program to find out the


// maximum product in the matrix
// which four elements are adjacent
// to each other in one direction
using System;
  
public class GFG {
      
    static int n = 5;
  
// Function to find max product
static int FindMaxProduct(int[,] arr, int n) 
{
    int max = 0, result;
  
    // iterate the rows
    for (int i = 0; i < n; i++) {
          
    // iterate the columns
    for (int j = 0; j < n; j++) {
          
        // 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 && (j - 3) >= 0) 
        {

1131
Chapter 160. Maximum product of 4 adjacent elements in matrix

        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
    static public void Main ()
    {
    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}};
                  
    Console.Write(FindMaxProduct(arr, n));
    }
}
  
// This code is contributed by Shrikant13

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

Improved By : shrikanth13, vt_m

Source

https://www.geeksforgeeks.org/maximum-product-of-4-adjacent-elements-in-matrix/

1134
Chapter 161

Maximum size rectangle binary


sub-matrix with all 1s

Maximum size rectangle binary sub-matrix with all 1s - GeeksforGeeks


Given a binary matrix, find the maximum size rectangle binary-sub-matrix with all 1’s.

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.

Step 1: Find maximum area for row[0]


Step 2:
for each row in 1 to N - 1
for each column in that row
if A[row][column] == 1
update A[row][column] with
A[row][column] += A[row - 1][column]
find area for that row
and update maximum area so far

1135
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s

Illustration :

step 1: 0 1 1 0 maximum area = 2


step 2:
row 1 1 2 2 1 area = 4, maximum area becomes 4
row 2 2 3 3 2 area = 8, maximum area becomes 8
row 3 3 4 0 0 area = 6, maximum area remains 8

Below is the implementation. It is strongly recommended to refer this post first as most of
the code taken from there.

C++

// C++ program to find largest rectangle with all 1s


// in a binary matrix
#include<bits/stdc++.h>
using namespace std;
  
// Rows and columns in input matrix
#define R 4
#define C 4
  
// Finds the maximum area under the histogram represented
// by histogram.  See below article for details.
// https://www.geeksforgeeks.org/largest-rectangle-under-histogram/
int maxHist(int row[])
{
    // Create an empty stack. The stack holds indexes of
    // hist[] array/ The bars stored in stack are always
    // in increasing order of their heights.
    stack<int> result;
  
    int top_val;     // Top of stack
  
    int max_area = 0; // Initialize max area in current
                      // row (or histogram)
  
    int area = 0;    // Initialize area with current top
  
    // Run through all bars of given histogram (or row)
    int i = 0;
    while (i < C)
    {
        // If this bar is higher than the bar on top stack,
        // push it to stack
        if (result.empty() || row[result.top()] <= row[i])

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

            // if A[i][j] is 1 then add A[i -1][j]


            if (A[i][j]) A[i][j] += A[i - 1][j];
  
  
        // Update result if area with current row (as last row)
        // of rectangle) is more
        result = max(result, maxHist(A[i]));
    }
  
    return result;
}
  
// Driver code
int main()
{
    int A[][C] = { {0, 1, 1, 0},
                   {1, 1, 1, 1},
                   {1, 1, 1, 1},
                   {1, 1, 0, 0},
                 };
  
    cout << "Area of maximum rectangle is "
         << maxRectangle(A);
  
    return 0;
}

Java

// Java program to find largest rectangle with all 1s


// in a binary matrix
import java.io.*;
import java.util.*;
   
class GFG 
{
    // Finds the maximum area under the histogram represented
    // by histogram.  See below article for details.
    // https://www.geeksforgeeks.org/largest-rectangle-under-histogram/
    static int maxHist(int R,int C,int row[])
    {
        // Create an empty stack. The stack holds indexes of
        // hist[] array/ The bars stored in stack are always
        // in increasing order of their heights.
        Stack<Integer> result = new Stack<Integer>();
       
        int top_val;     // Top of stack
       

1138
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s

        int max_area = 0; // Initialize max area in current


                          // row (or histogram)
       
        int area = 0;    // Initialize area with current top
       
        // Run through all bars of given histogram (or row)
        int i = 0;
        while (i < C)
        {
            // If this bar is higher than the bar on top stack,
            // push it to stack
            if (result.empty() || row[result.peek()] <= row[i])
                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.peek()];
                result.pop();
                area = top_val * i;
       
                if (!result.empty())
                    area = top_val * (i - result.peek() - 1 );
                max_area = Math.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.peek()];
            result.pop();
            area = top_val * i;
            if (!result.empty())
                area = top_val * (i - result.peek() - 1 );
       
            max_area = Math.max(area, max_area);
        }
        return max_area;
    }
  
    // Returns area of the largest rectangle with all 1s in 
    // A[][]

1139
Chapter 161. Maximum size rectangle binary sub-matrix with all 1s

    static int maxRectangle(int R,int C,int A[][])


    {
        // Calculate area for first row and initialize it as
        // result
        int result = maxHist(R,C,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++)
       
                // if A[i][j] is 1 then add A[i -1][j]
                if (A[i][j] == 1) A[i][j] += A[i - 1][j];
       
       
            // Update result if area with current row (as last
            // row of rectangle) is more
            result = Math.max(result, maxHist(R,C,A[i]));
        }
       
        return result;
    }
       
    // Driver code
    public static void main (String[] args) 
    {
        int R = 4;
        int C = 4;
  
        int A[][] = { {0, 1, 1, 0},
                      {1, 1, 1, 1},
                      {1, 1, 1, 1},
                      {1, 1, 0, 0},
                    };
        System.out.print("Area of maximum rectangle is " + 
                                  maxRectangle(R,C,A));
    }
}
   
// Contributed by Prakriti Gupta

Output :

Area of maximum rectangle is 8

Time Complexity : O(R x X)

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

Maximum size square


sub-matrix with all 1s

Maximum size square sub-matrix with all 1s - GeeksforGeeks


Given a binary matrix, find out the maximum size square sub-matrix with all 1s.
For example, consider the below binary matrix.

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.

1) Construct a sum matrix S[R][C] for the given M[R][C].


a) Copy first row and first columns as it is from M[][] to S[][]
b) For other entries, use following expressions to construct S[][]
If M[i][j] is 1 then
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
Else /*If M[i][j] is 0*/
S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print

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++

// C/C++ code for Maximum size square sub-matrix with all 1s


#include<stdio.h>
#define bool int
#define R 6
#define C 5
  
void printMaxSubSquare(bool M[R][C])
{
  int i,j;
  int S[R][C];
  int max_of_s, max_i, max_j; 
   
  /* Set first column of S[][]*/
  for(i = 0; i < R; i++)
     S[i][0] = M[i][0];
   
  /* Set first row of S[][]*/     
  for(j = 0; j < C; j++)
     S[0][j] = M[0][j];
       
  /* Construct other entries of S[][]*/
  for(i = 1; i < R; i++)
  {
    for(j = 1; j < C; j++)
    {
      if(M[i][j] == 1) 
        S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1;
      else
        S[i][j] = 0;
    }    
  } 

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

// JAVA Code for Maximum size square sub-matrix with all 1s


public class GFG
{
    // method for Maximum size square sub-matrix with all 1s
    static void printMaxSubSquare(int M[][])
    {
        int i,j;
        int R = M.length;         //no of rows in M[][]
        int C = M[0].length;     //no of columns in M[][]
        int S[][] = new int[R][C];     
          
        int max_of_s, max_i, max_j; 
        
        /* Set first column of S[][]*/
        for(i = 0; i < R; i++)
            S[i][0] = M[i][0];
        
        /* Set first row of S[][]*/    
        for(j = 0; j < C; j++)
            S[0][j] = M[0][j];
            
        /* Construct other entries of S[][]*/
        for(i = 1; i < R; i++)
        {
            for(j = 1; j < C; j++)
            {
                if(M[i][j] == 1) 
                    S[i][j] = Math.min(S[i][j-1],Math.min(S[i-1][j], S[i-1][j-1])) + 1;
                else
                    S[i][j] = 0;
            }    
        }     
         
        /* 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++)
            {

1145
Chapter 162. Maximum size square sub-matrix with all 1s

                if(max_of_s < S[i][j])


                {
                    max_of_s = S[i][j];
                    max_i = i; 
                    max_j = j;
                }        
            }                 
        }     
         
        System.out.println("Maximum size sub-matrix is: ");
        for(i = max_i; i > max_i - max_of_s; i--)
        {
            for(j = max_j; j > max_j - max_of_s; j--)
            {
                System.out.print(M[i][j] + " ");
            }  
            System.out.println();
        }  
    }    
      
    // Driver program 
    public static void main(String[] args) 
    {
        int M[][] =  {{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},
                      {0, 0, 0, 0, 0}};
               
        printMaxSubSquare(M);
    }
  
}

Python3

# Python3 code for Maximum size


# square sub-matrix with all 1s
  
def printMaxSubSquare(M):
    R = len(M) # no. of rows in M[][]
    C = len(M[0]) # no. of columns in M[][]
  
    S = [[0 for k in range(C)] for l in range(R)]
    # here we have set the first row and column of S[][]
  
    # Construct other entries

1146
Chapter 162. Maximum size square sub-matrix with all 1s

    for i in range(1, R):


        for j in range(1, C):
            if (M[i][j] == 1):
                S[i][j] = min(S[i][j-1], S[i-1][j],
                            S[i-1][j-1]) + 1
            else:
                S[i][j] = 0
      
    # Find the maximum entry and
    # indices of maximum entry in S[][]
    max_of_s = S[0][0]
    max_i = 0
    max_j = 0
    for i in range(R):
        for j in range(C):
            if (max_of_s < S[i][j]):
                max_of_s = S[i][j]
                max_i = i
                max_j = j
  
    print("Maximum size sub-matrix is: ")
    for i in range(max_i, max_i - max_of_s, -1):
        for j in range(max_j, max_j - max_of_s, -1):
            print (M[i][j], end = " ")
        print("")
  
# Driver Program
M = [[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],
    [0, 0, 0, 0, 0]]
  
printMaxSubSquare(M)
  
# This code is contributed by Soumen Ghosh

Output:

Maximum size sub-matrix is:


1 1 1
1 1 1
1 1 1

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

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:

Input : mat[][] = { {1, 0, 0, 1},


{0, 1, 1, 1},
{1, 0, 0, 0},
{0, 1, 0, 1} }
Output : 9
The sub-matrix defined by the boundary values (1, 1) and (3, 3).
{ {1, 0, 0, 1},
{0, 1, 1, 1},
{1, 0, 0, 0},
{0, 1, 0, 1} }

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:

// C++ implementation to find


// the maximum area sub-matrix
// having count of 1's
// one more than count of 0's
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 10
  
// function to find the length of longest
// subarray having count of 1's one more
// than count of 0's
int lenOfLongSubarr(int arr[], int n,
                    int& start, int& finish)
{
    // unordered_map 'um' implemented as
    // hash table
    unordered_map<int, int> um;
    int sum = 0, maxLen = 0;
  
    // traverse the given array
    for (int i = 0; i < n; i++) {
  
        // accumulating sum
        sum += arr[i];
  
        // when subarray starts form index '0'
        if (sum == 1) {
            start = 0;
            finish = i;
            maxLen = i + 1;
        }
  
        // make an entry for 'sum' if it is
        // not present in 'um'
        else if (um.find(sum) == um.end())
            um[sum] = i;
  

1150
Chapter 163. Maximum sub-matrix area having count of 1’s one more than count of 0’s

        // check if 'sum-1' is present in 'um'


        // or not
        if (um.find(sum - 1) != um.end()) {
  
            // update 'start', 'finish'
            // and maxLength
            if (maxLen < (i - um[sum - 1]))
                start = um[sum - 1] + 1;
            finish = i;
            maxLen = i - um[sum - 1];
        }
    }
  
    // required maximum length
    return maxLen;
}
  
// function to find the maximum
// area sub-matrix having
// count of 1's one more than count of 0's
void largestSubmatrix(int mat[SIZE][SIZE], int n)
{
    // variables to store final
    // and intermediate results
    int finalLeft, finalRight, finalTop, finalBottom;
    int temp[n], maxArea = 0, len, start, finish;
  
    // set the left column
    for (int 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 (int right = left; right < n; right++) {
  
            // Calculate sum between current left and right
            // for every row 'i', consider '0' as '-1'
            for (int i = 0; i < n; ++i)
                temp[i] += mat[i][right] == 0 ? -1 : 1;
  
            // function to set the 'start' and 'finish'
            // variables having index values of
            // temp[] which contains the longest
            // subarray of temp[] having count of 1's
            // one more than count of 0's
            len = lenOfLongSubarr(temp, n, start, finish);

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:

(Top, Left): (1, 1)


(Bottom, Right): (3, 3)
Maximum area: 9

Time Complexity: O(N3 ).


Auxiliary Space: O(N).

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

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++

// C++ program to find maximum sum in a grid such that


// no two elements are adjacent.
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
  
// Function to find max sum without adjacent
int maxSum(int grid[2][MAX], int n)
{
    // Sum including maximum element of first column
    int incl = max(grid[0][0], grid[1][0]);
  
    // Not including first column's element
    int excl = 0, excl_new;
  
    // Traverse for further elements
    for (int i = 1; i<n; i++ )
    {
        // Update max_sum on including or excluding
        // of previous column
        excl_new = max(excl, incl);
  
        // Include current column. Add maximum element
        // from both row of current column
        incl = excl + max(grid[0][i], grid[1][i]);
  
        // If current column doesn't to be included
        excl = excl_new;
    }
  
    // Return maximum of excl and incl
    // As that will be the maximum sum
    return max(excl, incl);
}
  
// Driver code
int main()
{
    int grid[2][MAX] = {{ 1, 2, 3, 4, 5},
                        { 6, 7, 8, 9, 10}};
  

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

// JAVA Code for Maximum sum in a 2 x n grid


// such that no two elements are adjacent
import java.util.*;
  
class GFG {
      
    // Function to find max sum without adjacent
    public static int maxSum(int grid[][], int n)
    {
        // Sum including maximum element of first
        // column
        int incl = Math.max(grid[0][0], grid[1][0]);
       
        // Not including first column's element
        int excl = 0, excl_new;
       
        // Traverse for further elements
        for (int i = 1; i < n; i++ )
        {
            // Update max_sum on including or 
            // excluding of previous column
            excl_new = Math.max(excl, incl);
       
            // Include current column. Add maximum element
            // from both row of current column
            incl = excl + Math.max(grid[0][i], grid[1][i]);
       
            // If current column doesn't to be included
            excl = excl_new;
        }
       
        // Return maximum of excl and incl
        // As that will be the maximum sum
        return Math.max(excl, incl);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
         int grid[][] = {{ 1, 2, 3, 4, 5},

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

Time Complexity : O(n)

Source

https://www.geeksforgeeks.org/maximum-sum-2-x-n-grid-no-two-elements-adjacent/

1157
Chapter 165

Maximum sum of elements from


each row in the matrix

Maximum sum of elements from each row in the matrix - GeeksforGeeks


Given a matrix, find the maximum sum we can have by selecting just one element from
every row. Condition is element selected from nth row must be strictly greater than element
from (n-1)th row, else no element must be taken from row. Print the sum if possible else
print -1.
Examples :

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

// CPP Program to find row-wise maximum element


// sum considering elements in increasing oder.
#include <bits/stdc++.h>
#define N 3
using namespace std;
  
// Function to perform given task
int getGreatestSum(int a[][N])
{
    // Getting the maximum element from last row
    int prev_max = 0;
    for (int 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
    int sum = prev_max;
    for (int i = N - 2; i >= 0; i--) {
  
        // Maximum of current row.
        int curr_max = INT_MIN;
        for (int j = 0; j < N; j++)
            if (prev_max > a[i][j] && a[i][j] > curr_max)
                curr_max = a[i][j];
  
        // If we could not an element smaller
        // than prev_max.
        if (curr_max == INT_MAX)
            return -1;
  
        prev_max = curr_max;
        sum += prev_max;
    }
    return sum;
}
  
// Driver code
int main()
{
    int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    cout << getGreatestSum(a) << endl;
    int b[3][3] = { { 4, 5, 6 }, { 4, 5, 6 }, { 4, 5, 6 } };
    cout << getGreatestSum(b) << endl;
    return 0;
}

Java

1159
Chapter 165. Maximum sum of elements from each row in the matrix

// Java Program to find row-wise maximum


// element sum considering elements in 
// increasing oder.
class GFG {
      
    static final int N = 3;
      
    // Function to perform given task
    static int getGreatestSum(int a[][]) {
          
        // Getting the maximum element from
        // last row
        int prev_max = 0;
  
        for (int 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
        int sum = prev_max;
  
        for (int i = N - 2; i >= 0; i--) {
      
            // Maximum of current row.
            int curr_max = -2147483648;
  
            for (int j = 0; j < N; j++)
                if (prev_max > a[i][j] && 
                        a[i][j] > curr_max)
                    curr_max = a[i][j];
          
            // If we could not an element smaller
            // than prev_max.
            if (curr_max == 2147483647)
                return -1;
          
            prev_max = curr_max;
            sum += prev_max;
        }
          
        return sum;
    }
      
    // Driver Program to test above function
    public static void main(String arg[]) {
          
        int a[][] = {{1, 2, 3}, 

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

# Python Program to find


# row-wise maximum element
# sum considering elements
# in increasing oder.
  
N = 3
  
# Function to perform given task
def getGreatestSum(a):
  
    # Getting the maximum
    # element from last row
    prev_max = 0
    for j in range(N):
        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 in range(N - 2,-1,-1):
   
        #Maximum of current row.
        curr_max = -2147483648
        for j in range(N):
            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 == +2147483647):
            return -1
   

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#

// C# Program to find row-wise maximum


// element sum considering elements in 
// increasing oder.
using System;
  
class GFG {
      
    static int N = 3;
      
    // Function to perform given task
    static int getGreatestSum(int [,]a) {
          
        // Getting the maximum element from
        // last row
        int prev_max = 0;
  
        for (int 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
        int sum = prev_max;
  

1162
Chapter 165. Maximum sum of elements from each row in the matrix

        for (int i = N - 2; i >= 0; i--) {


      
            // Maximum of current row.
            int curr_max = -2147483648;
  
            for (int j = 0; j < N; j++)
                if (prev_max > a[i, j] && 
                        a[i, j] > curr_max)
                    curr_max = a[i, j];
          
            // If we could not an element smaller
            // than prev_max.
            if (curr_max == 2147483647)
                return -1;
          
            prev_max = curr_max;
            sum += prev_max;
        }
          
        return sum;
    }
      
    // Driver Program 
    public static void Main() {
          
        int [,]a = {{1, 2, 3}, 
                    {4, 5, 6}, 
                    {7, 8, 9}};
        Console.WriteLine(getGreatestSum(a));
          
        int [,]b = {{4, 5, 6}, 
                    {4, 5, 6}, 
                    {4, 5, 6}};
        Console.WriteLine(getGreatestSum(b));
    }
}
  
// This code is contributed by vt_m.

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

echo getGreatestSum($b) ,"\n";


  
// This code is contributed by anuj_67.
?>

Output :

18
15

Improved By : vt_m

Source

https://www.geeksforgeeks.org/maximum-sum-elements-row-matrix/

1165
Chapter 166

Maximum sum of hour glass in


matrix

Maximum sum of hour glass in matrix - GeeksforGeeks


Given a 2D matrix, the task is that we find maximum sum of a hour glass.

An hour glass is made of 7 cells


in following form.
A B C
D
E F G

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++

// C++ program to find maximum sum of hour


// glass in matrix
#include<bits/stdc++.h>
using namespace std;
const int R = 5;
const int C = 5;
  

1167
Chapter 166. Maximum sum of hour glass in matrix

// Returns maximum sum of hour glass in ar[][]


int findMaxSum(int mat[R][C])
{
    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 = INT_MIN;
    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 = max(max_sum, sum);
        }
    }
    return max_sum;
}
  
// Driver code
int main()
{
    int mat[][C] = {{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)
        cout << "Not possible" << endl;
    else
        cout << "Maximum sum of hour glass = "
             << res << endl;
    return 0;
}

Java

// Java program to find maximum 


// sum of hour glass in matrix

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#

// C# program to find maximum 


// sum of hour glass in matrix
using System;
  
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 = int.MinValue;
    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);
        }

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:

Maximum sum of hour glass = 13

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

Maximum sum path in a matrix


from top to bottom

Maximum sum path in a matrix from top to bottom - GeeksforGeeks


Consider a n*n matrix. Suppose each cell in the matrix has a value assigned. We can go
from each cell in row i to a diagonally higher cell in row i+1 only [i.e from cell(i, j) to
cell(i+1, j-1) and cell(i+1, j+1) only]. Find the path from the top row to the bottom row
following the aforementioned condition such that the maximum sum is obtained.
Examples:

Input : mat[][] = { {5, 6, 1, 7},


{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }
Output : 28

{5, 6, 1, 7},
{-2, 10, 8, -1},
{3, -7, -9, 11},
{12, -4, 2, 6} }

The highlighted numbers from top to bottom


gives the required maximum sum path.
(7 + 8 + 11 + 2) = 28

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

// C++ implementation to find the maximum sum


// path in a matrix
#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 10
  
// function to find the maximum sum
// path in a matric
int maxSum(int mat[SIZE][SIZE], int n)
{
    // if there is a single element only
    if (n == 1)
        return mat[0][0];
  
    // dp[][] matrix to store the results
    // of each iteration
    int dp[n][n];
    int maxSum = INT_MIN, max;
  
    // base case, copying elements of
    // last row
    for (int 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 (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j < n; j++) {
            max = INT_MIN;
  
            // finding the maximum diagonal element in the
            // (i+1)th row if that cell exists
            if (((j - 1) >= 0) && (max < dp[i + 1][j - 1]))
                max = dp[i + 1][j - 1];
            if (((j + 1) < n) && (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 (int j = 0; j < n; j++)
        if (maxSum < dp[0][j])

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

// Java implementation to find the 


// maximum sum path in a matrix
import java.io.*;
  
class MaxSumPath {
//int mat[][];
  
// function to find the maximum 
// sum path in a matrix
static int maxSum(int[][] mat, int n)
{
    // if there is a single element only
    if (n == 1)
        return mat[0][0];
  
    // dp[][] matrix to store the results
    // of each iteration
    int dp[][] = new int[n][n];
    int maxSum = Integer.MIN_VALUE, max;
  
    // base case, copying elements of
    // last row
    for (int j = 0; j < n; j++)
        dp[n - 1][j] = mat[n - 1][j];
  

1174
Chapter 167. Maximum sum path in a matrix from top to bottom

    // building up the dp[][] matrix 


    // from bottom to the top row
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j < n; j++) {
            max = Integer.MIN_VALUE;
  
            // finding the maximum diagonal 
            // element in the (i+1)th row 
            // if that cell exists
            if (((j - 1) >= 0) && 
                 (max < dp[i + 1][j - 1]))
                 max = dp[i + 1][j - 1];
            if (((j + 1) < n) && 
                (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 (int j = 0; j < n; j++)
        if (maxSum < dp[0][j])
            maxSum = dp[0][j];
  
    // required maximum sum
    return maxSum;
}
  
    // Driver code
    public static void main (String[] args) {
      
    int mat[][] = { { 5, 6, 1, 7 },
                    { -2, 10, 8, -1 },
                    { 3, -7, -9, 11 },
                    { 12, -4, 2, 6 } };
    int n = 4;
  
    System.out.println("Maximum Sum = "+
                        maxSum(mat , n));
  
    }
}
  
// This code is contributed by Prerna Saini

1175
Chapter 167. Maximum sum path in a matrix from top to bottom

C#

// C# implementation to find the 


// maximum sum path in a matrix
using System;
  
class MaxSumPath 
{
    //int mat[][];
      
    // function to find the maximum 
    // sum path in a matrix
    static int maxSum(int[,] mat, int n)
    {
        // if there is a single element only
        if (n == 1)
            return mat[0, 0];
      
        // dp[][] matrix to store the results
        // of each iteration
        int [,]dp = new int[n, n];
        int maxSum = int.MinValue, max;
      
        // base case, copying elements of
        // last row
        for (int 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 (int i = n - 2; i >= 0; i--)
        {
            for (int j = 0; j < n; j++) 
            {
                max = int.MinValue;
      
                // finding the maximum diagonal 
                // element in the (i+1)th row 
                // if that cell exists
                if (((j - 1) >= 0) && 
                    (max < dp[i + 1, j - 1]))
                    max = dp[i + 1, j - 1];
                if (((j + 1) < n) && 
                    (max < dp[i + 1, j + 1]))
                    max = dp[i + 1, j + 1];
      
                // adding that 'max' element
                // to the mat[i][j] element

1176
Chapter 167. Maximum sum path in a matrix from top to bottom

                dp[i, j] = mat[i, j] + max;


            }
        }
      
        // finding the maximum value from
        // the first row of dp[][]
        for (int j = 0; j < n; j++)
            if (maxSum < dp[0, j])
                maxSum = dp[0, j];
      
        // required maximum sum
        return maxSum;
    }
  
    // Driver code
    public static void Main () {
      
    int [,]mat = { { 5, 6, 1, 7 },
                    { -2, 10, 8, -1 },
                    { 3, -7, -9, 11 },
                    { 12, -4, 2, 6 } };
    int n = 4;
  
    Console.WriteLine("Maximum Sum = "+
                        maxSum(mat , n));
  
    }
}
  
// This code is contributed by vt_m

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

Time Complexity: O(n2 ).


Auxiliary Space: O(n2 ).
Exercise: Try to solve it in auxiliary space of O(n).
Improved By : vt_m

Source

https://www.geeksforgeeks.org/maximum-sum-path-matrix-top-bottom/

1179
Chapter 168

Maximum sum rectangle in a


2D matrix | DP-27

Maximum sum rectangle in a 2D matrix | DP-27 - GeeksforGeeks


Given a 2D array, find the maximum sum subarray in it. For example, in the following
2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this
subarray is 29.

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.

// Program to find maximum sum subarray in a given 2D array


#include <stdio.h>
#include <string.h>
#include <limits.h>
#define ROW 4
#define COL 5
  
// Implementation of Kadane's algorithm for 1D array. The function 
// returns the maximum sum and stores starting and ending indexes of the 
// maximum sum subarray at addresses pointed by start and finish pointers 
// respectively.
int kadane(int* arr, int* start, int* finish, int n)
{
    // initialize sum, maxSum and
    int sum = 0, maxSum = INT_MIN, i;
  
    // Just some initial value to check for all negative values case
    *finish = -1;
  
    // local variable
    int local_start = 0;
  
    for (i = 0; i < n; ++i)
    {
        sum += arr[i];
        if (sum < 0)
        {
            sum = 0;
            local_start = i+1;
        }
        else if (sum > maxSum)
        {
            maxSum = sum;
            *start = local_start;
            *finish = i;
        }
    }
  
     // There is at-least one non-negative number
    if (*finish != -1)

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

            // update maxSum and other output values


            if (sum > maxSum)
            {
                maxSum = sum;
                finalLeft = left;
                finalRight = right;
                finalTop = start;
                finalBottom = finish;
            }
        }
    }
  
    // Print final values
    printf("(Top, Left) (%d, %d)\n", finalTop, finalLeft);
    printf("(Bottom, Right) (%d, %d)\n", finalBottom, finalRight);
    printf("Max sum is: %d\n", maxSum);
}
  
// Driver program to test above functions
int main()
{
    int M[ROW][COL] = {{1, 2, -1, -4, -20},
                       {-8, -3, 4, 2, 1},
                       {3, 8, 10, 1, 3},
                       {-4, -1, 1, 7, -6}
                      };
  
    findMaxSum(M);
  
    return 0;
}

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

                            {3, 8, 10, 1, 3},


                            {-4, -1, 1, 7, -6}
                            });
    }
      
    /**
     * To find maxSum in 1d array
     * 
     * return {maxSum, left, right}
     */ 
    public static int[] kadane(int[] a) {
        //result[0] == maxSum, result[1] == start, result[2] == end;
        int[] result = new int[]{Integer.MIN_VALUE, 0, -1};
        int currentSum = 0;
        int localStart = 0;
      
        for (int i = 0; i < a.length; i++) {
            currentSum += a[i];
            if (currentSum < 0) {
                  currentSum = 0;
                localStart = i + 1;
              } else if (currentSum > result[0]) {
                result[0] = currentSum;
                result[1] = localStart;
                result[2] = i;
              }
        }
          
        //all numbers in a are negative
        if (result[2] == -1) {
            result[0] = 0;
            for (int i = 0; i < a.length; i++) {
                if (a[i] > result[0]) {
                    result[0] = a[i];
                    result[1] = i;
                    result[2] = i;
                }
            }
        }
          
        return result;
      }
  
    /**
     * To find and print maxSum, (left, top),(right, bottom)
     */
    public static void findMaxSubMatrix(int[][] a) {
        int cols = a[0].length;

1184
Chapter 168. Maximum sum rectangle in a 2D matrix | DP-27

        int rows = a.length;


        int[] currentResult;
        int maxSum = Integer.MIN_VALUE;
        int left = 0;
        int top = 0;
        int right = 0;
        int bottom = 0;
          
        for (int leftCol = 0; leftCol < cols; leftCol++) {
            int[] tmp = new int[rows];
      
              for (int rightCol = leftCol; rightCol < cols; rightCol++) {
          
                for (int i = 0; i < rows; i++) {
                      tmp[i] += a[i][rightCol];
                }
                currentResult = kadane(tmp);
                if (currentResult[0] > maxSum) {
                    maxSum = currentResult[0];
                    left = leftCol;
                    top = currentResult[1];
                    right = rightCol;
                    bottom = currentResult[2];
                }
            }
        }
              System.out.println("MaxSum: " + maxSum + 
                                ", range: [(" + left + ", " + top + 
                                  ")(" + right + ", " + bottom + ")]");
    }
}
// Thanks to Ilia Savin for contributing this code.

Output:

(Top, Left) (1, 1)


(Bottom, Right) (3, 3)
Max sum is: 29

Time Complexity: O(n^3)


This article is compiled byAashish Barnwal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Gaurav Kumar 33

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

Maximum value in a matrix


which contain intersecting
concentric submatrix

Maximum value in a matrix which contain intersecting concentric submatrix - GeeksforGeeks


Suppose a matrix of size N X N which contain concentric square submatrices centered at
(xi , yi ), where xi is the row number of center of ith concentric square matrix and yi is the
column number of center of ith concentric square matrix. Concentric square matrix is of
the form:

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++

//C++ Program to find the maximum value in a matrix


//which contain intersecting concentric submatrix
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100
  
// Return the maximum value in intersecting
// concentric submatrix.
int maxValue(int n, int m, int x[], int y[], int a[])
{
    int c[MAXN][MAXN] = { 0 };
  
    // 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 = abs(p - x[i]);
  
                // finding y distance.
                int dy = abs(q - y[i]);

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

// Java Program to find the 


// maximum value in a matrix 
// which contain intersecting 
// concentric submatrix
import java.io.*;
  
class GFG
{
static int MAXN = 100;
  
// Return the maximum value 
// in intersecting

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

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:

• It should begin from top left element.


• The path can end at any element of last row.
• We can move to following two cells from a cell (i, j).
1. Down Move : (i+1, j)
2. Diagonal Move : (i+1, j+1)

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

The above problem can be recursively defined.

1192
Chapter 170. Maximum weight path ending at any element of last row in a matrix

Let maxCost(i, j) be the cost maximum cost to


reach mat[i][j]. Since end point can be any point
in last row, we finally return maximum of all values
maxCost(N-1, j) where j varies from 0 to N-1.

If i == 0 and j == 0
maxCost(0, 0) = mat[0][0]

// We can traverse through first column only by


// down move
Else if j = 0
maxCost(i, 0) = maxCost(i-1, 0) + mat[i][0]

// In other cases, a cell mat[i][j] can be reached


// through previous two cells ma[i-1][j] and
// mat[i-1][j-1]
Else
maxCost(i, j) = mat[i][j] + max(maxCost(i-1, j),
maxCost(i-1, j-1)),

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++

// C++ program to find the path having the


// maximum weight in matrix
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
  
/* Function which return the maximum weight
   path sum */
int maxCost(int mat[][MAX], int N)
{
    // creat 2D matrix to store the sum of the path
    int dp[N][N];
    memset(dp, 0, sizeof(dp));
  
    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];
  

1193
Chapter 170. Maximum weight path ending at any element of last row in a matrix

    // Calculate rest paht 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] +
                    max(dp[i-1][j-1], dp[i-1][j]);
  
    // find the max weight path sum to rech
    // 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
int main()
{
    int mat[MAX][MAX] = {  { 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;
    cout << "Maximum Path Sum : "
        << maxCost(mat, N)<<endl;
    return 0;
}

Java

// JAVA Code for Maximum weight path ending at 


// any element of last row in a matrix
import java.util.*;
  
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];
          

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

# Python3 program to find the path 


# having the maximum weight in matrix
  
MAX = 1000
  

1195
Chapter 170. Maximum weight path ending at any element of last row in a matrix

# Function which return the 


# maximum weight path sum
def maxCost(mat, N):
      
    # creat 2D matrix to store the sum of the path
    dp = [[0 for i in range(N)] for j in range(N)]
  
    dp[0][0] = mat[0][0]
  
    # Initialize first column of total weight
    # array (dp[i to N][0])
    for i in range(1, N):
        dp[i][0] = mat[i][0] + dp[i - 1][0]
  
    # Calculate rest path sum of weight matrix
    for i in range(1, N):
        for j in range(1, min(i + 1, N)):
            dp[i][j] = mat[i][j] + \
                       max(dp[i - 1][j - 1],
                           dp[i - 1][j])
  
    # find the max weight path sum to reach
    # the last row
    result = 0
    for i in range(N):
        if (result < dp[N - 1][i]):
            result = dp[N - 1][i]
  
    # return maximum weight path sum
    return result
  
# Driver Program
  
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]]
  
N = 5
print('Maximum Path Sum :', maxCost(mat, N))
  
# This code is contributed by Soumen Ghosh.

C#

// C# Code for Maximum weight path


// ending at any element of last

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:

Maximum Path Sum : 255

Time complexity : O(N*N)


Improved By : KRV

Source

https://www.geeksforgeeks.org/maximum-weight-path-ending-element-last-row-matrix/

1198
Chapter 171

Mean and Median of a matrix

Mean and Median of a matrix - GeeksforGeeks


Given a sorted matrix of size n*n. Calculate the mean and median of the matrix .
Examples:

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.

Median of a sorted matrix is calculated as:


1. When n is odd
median is mat[n/2][n/2]
2. When n is even, median is average
of middle two elements.

1199
Chapter 171. Mean and Median of a matrix

Middle two elements can be found at indexes


a[(n-2)/2][n-1] and a[n/2][0]

If given matrix is unsorted, we can find its median by first sorting the matrix.

C++

// CPP program to find mean and median


// of sorted square matrix.
#include <bits/stdc++.h>
using namespace std;
  
const int N = 4;
  
// Returns mean of a given matrix of
// size n x n.
double findMean(int a[][N])
{
    int sum = 0;
  
    // total sum calculation of matrix
    for (int i=0; i<N; i++)
       for (int j=0; j<N; j++)
          sum += a[i][j];
  
    return (double)sum/(N*N);
}
  
// Function for calculating median
double findMedian(int a[][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 program
int main()
{
    int a[N][N]= {{1, 2, 3, 4},
                   {5, 6, 7, 8},
                   {9, 10, 11, 12},
                   {13, 14, 15, 16}};
    cout << "Mean : " << findMean(a) << endl

1200
Chapter 171. Mean and Median of a matrix

         << "Median : "<< findMedian(a) << endl;


    return 0;
}

Java

// Java program to find mean and median


// of sorted square matrix.
import java.io.*;
  
class GFG
{
      
// Returns mean of a given 
// matrix of size n x n.
static double findMean(int a[][], 
                    int n)
{
    int sum = 0;
    int N=n;
  
    // total sum calculation of matrix
    for (int i = 0; i < N; i++)
    for (int j = 0; j < N; j++)
        sum += a[i][j];
  
    return (double)sum / (N * N);
}
  
// Function for calculating median
static double findMedian(int a[][], int n)

    int N = 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);
    return 0;
}
  
    // Driver Code
    public static void main (String[] args)
    {
        int a[][]= {{1, 2, 3, 4},
                    {5, 6, 7, 8},

1201
Chapter 171. Mean and Median of a matrix

                    {9, 10, 11, 12},


                    {13, 14, 15, 16}};
              
        int n = a.length;
        System.out.println("Mean   : " + 
                            findMean(a, n));
        System.out.println("Median : " + 
                            findMedian(a, n));
    }
          
          
}
  
// This code is contributed by KRV.

C#

// C# program to find mean and median


// of sorted square matrix.
using System;
  
class GFG {
      
    // Returns mean of a given 
    // matrix of size n x n.
    static double findMean(int [,]a, int n)
    {
        int sum = 0;
        int N = n;
      
        // total sum calculation of matrix
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
                sum += a[i,j];
      
        return (double)sum / (N * N);
    }
      
    // Function for calculating median
    static double findMedian(int [,]a, int n)
    { 
        int N = n;
          
        if (N % 2 != 0)
        return a[N / 2,N / 2];
      
        if (N % 2 == 0)
        return ( a[(N - 2) / 2, (N - 1)] +

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

Improved By : KRV, vt_m, Sam007

Source

https://www.geeksforgeeks.org/mean-median-matrix/

1204
Chapter 172

Min Cost Path | DP-6

Min Cost Path | DP-6 - GeeksforGeeks


Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns
cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a
cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs
on that path (including both source and destination). You can only traverse down, right
and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1)
and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.
For example, in the following figure, what is the minimum cost path to (2, 2)?

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.

/* A Naive recursive implementation of MCP(Minimum Cost Path) problem */


#include<stdio.h>
#include<limits.h>
#define R 3
#define C 3
  
int min(int x, int y, int z);
  
/* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*/
int minCost(int cost[R][C], int m, int n)
{
   if (n < 0 || m < 0)
      return INT_MAX;
   else if (m == 0 && n == 0)
      return cost[m][n];
   else
      return cost[m][n] + min( 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 */
int min(int x, int y, int z)
{
   if (x < y)
      return (x < z)? x : z;
   else
      return (y < z)? y : z;
}
  
/* Driver program to test above functions */
int main()
{
   int cost[R][C] = { {1, 2, 3},
                      {4, 8, 2},

1206
Chapter 172. Min Cost Path | DP-6

                      {1, 5, 3} };
   printf(" %d ", minCost(cost, 2, 2));
   return 0;
}

Java

/* A Naive recursive implementation of


MCP(Minimum Cost Path) problem */
public class GFG {
  
    /* A utility function that returns 
    minimum of 3 integers */
    static int min(int x, int y, int z)
    {
        if (x < y)
            return (x < z) ? x : z;
        else
            return (y < z) ? y : z;
    } 
      
    /* Returns cost of minimum cost path 
    from (0,0) to (m, n) in mat[R][C]*/
    static int minCost(int cost[][], int m,
                                     int n)
    {
        if (n < 0 || m < 0)
            return Integer.MAX_VALUE;
        else if (m == 0 && n == 0)
            return cost[m][n];
        else
            return cost[m][n] + 
                min( minCost(cost, m-1, n-1),
                     minCost(cost, m-1, n), 
                     minCost(cost, m, n-1) );
    }
  
    // Driver code
    public static void main(String args[]) 
    {
          
        int cost[][] = { {1, 2, 3},
                         {4, 8, 2},
                         {1, 5, 3} };
                           
        System.out.print(minCost(cost, 2, 2));
    }
}

1207
Chapter 172. Min Cost Path | DP-6

  
// This code is contributed by Sam007

Python3

# A Naive recursive implementation of MCP(Minimum Cost Path) problem


R = 3
C = 3
import sys
  
# Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]
def minCost(cost, m, n):
    if (n < 0 or m < 0):
        return sys.maxsize
    elif (m == 0 and n == 0):
        return cost[m][n]
    else:
        return cost[m][n] + min( 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 */
def min(x, y, z):
    if (x < y):
        return x if (x < z) else z
    else:
        return y if (y < z) else z
  
  
# 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
# Smitha Dinesh Semwal

C#

/* A Naive recursive implementation of


MCP(Minimum Cost Path) problem */
using System;
  
class GFG
{
  

1208
Chapter 172. Min Cost Path | DP-6

    /* A utility function that 


    returns minimum of 3 integers */
    static int min(int x, 
                   int y, int z)
    {
        if (x < y)
            return ((x < z) ? x : z);
        else
            return ((y < z) ? y : z);
    } 
      
    /* Returns cost of minimum 
    cost path from (0,0) to 
    (m, n) in mat[R][C]*/
    static int minCost(int [,]cost, 
                       int m , int n)
    {
        if (n < 0 || m < 0)
            return int.MaxValue;
        else if (m == 0 && n == 0)
            return cost[m, n];
        else
            return cost[m, n] + 
                   min(minCost(cost, m - 1, n - 1), 
                   minCost(cost, m - 1, n), 
                   minCost(cost, m, n - 1) );
    }
  
    // Driver code
    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 shiv_bhakt.

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++

/* Dynamic Programming implementation of MCP problem */


#include<stdio.h>
#include<limits.h>
#define R 3
#define C 3
  
int min(int x, int y, int z);
  
int minCost(int cost[R][C], int m, int n)
{
     int i, j;
  
     // 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 the program simple and make it working on all compilers.
     int tc[R][C];  
  
     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++)

1211
Chapter 172. Min Cost Path | DP-6

        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];
}
  
/* A utility function that returns minimum of 3 integers */
int min(int x, int y, int z)
{
   if (x < y)
      return (x < z)? x : z;
   else
      return (y < z)? y : z;
}
  
/* Driver program to test above functions */
int main()
{
   int cost[R][C] = { {1, 2, 3},
                      {4, 8, 2},
                      {1, 5, 3} };
   printf(" %d ", minCost(cost, 2, 2));
   return 0;
}

Java

/* Java program for Dynamic Programming implementation


   of Min Cost Path problem */
import java.util.*;
  
class MinimumCostPath
{
    /* A utility function that returns minimum of 3 integers */
    private static int min(int x, int y, int z)
    {
        if (x < y)
            return (x < z)? x : z;
        else
            return (y < z)? y : z;
    }
  
    private static int minCost(int cost[][], int m, int n)
    {
        int i, j;
        int tc[][]=new int[m+1][n+1];

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

# Dynamic Programming Python implementation of Min Cost Path


# problem
R = 3
C = 3
  
def minCost(cost, m, n):
  
    # Instead of following line, we can use int tc[m+1][n+1] or
    # dynamically allocate memoery to save space. The following
    # line is used to keep te program simple and make it working
    # on all compilers.
    tc = [[0 for x in range(C)] for x in range(R)]
  
    tc[0][0] = cost[0][0]

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#

// C# program for Dynamic Programming implementation


// of Min Cost Path problem 
using System;
  
class GFG
{
    // A utility function that 
    // returns minimum of 3 integers 
    private static int min(int x, int y, int z)
    {
        if (x < y)
            return (x < z)? x : z;
        else
            return (y < z)? y : z;
    }
  
    private static int minCost(int [,]cost, int m, int n)
    {
        int i, j;
        int [,]tc=new int[m+1,n+1];
  
        tc[0,0] = cost[0,0];

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

    // the program simple and make


    // it working on all compilers.
    $tc;
    for ($i = 0; $i <= $R; $i++)
    for ($j = 0; $j <= $C; $j++)
    $tc[$i][$j] = 0; 
  
    $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++)
          
            // returns minimum of 3 integers 
            $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 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:

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

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:

A cost grid is given in below diagram, minimum


cost to reach bottom right from top left
is 327 (= 31 + 10 + 13 + 47 + 65 + 12 + 18 +
6 + 33 + 11 + 20 + 41 + 20)

The chosen least cost path is shown in green.

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.

// C++ program to get least cost path in a grid from


// top-left to bottom-right
#include <bits/stdc++.h>
using namespace std;
  
#define ROW 5
#define COL 5
  
// structure for information of each cell
struct cell
{
    int x, y;
    int distance;
    cell(int x, int y, int distance) :
        x(x), y(y), distance(distance) {}
};
  
// Utility method for comparing two cells
bool operator<(const cell& a, const cell& b)
{
    if (a.distance == b.distance)
    {
        if (a.x != b.x)
            return (a.x < b.x);
        else
            return (a.y < b.y);
    }
    return (a.distance < b.distance);
}
  
// Utility method to check whether a point is
// inside the grid or not
bool isInsideGrid(int i, int j)
{
    return (i >= 0 && i < COL && j >= 0 && j < ROW);
}
  
// Method returns minimum cost to reach bottom
// right from top left
int shortest(int grid[ROW][COL], int row, int col)

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

                // update the distance and insert new updated


                // cell in set
                dis[x][y] = dis[k.x][k.y] + grid[x][y];
                st.insert(cell(x, y, dis[x][y]));
            }
        }
    }
  
    // uncomment below code to print distance
    // of each cell from (0, 0)
    /*
    for (int i = 0; i < row; i++, cout << endl)
        for (int j = 0; j < col; j++)
            cout << dis[i][j] << " ";
    */
    // dis[row - 1][col - 1] will represent final
    // distance of bottom right cell from top left cell
    return dis[row - 1][col - 1];
}
  
// Driver code to test above methods
int main()
{
    int grid[ROW][COL] =
    {
        31, 100, 65, 12, 18,
        10, 13, 47, 157, 6,
        100, 113, 174, 11, 33,
        88, 124, 41, 20, 140,
        99, 32, 111, 41, 20
    };
  
    cout << shortest(grid, ROW, COL) << endl;
    return 0;
}

Output:

327

Source

https://www.geeksforgeeks.org/minimum-cost-path-left-right-bottom-moves-allowed/

1221
Chapter 174

Minimum Initial Points to


Reach Destination

Minimum Initial Points to Reach Destination - GeeksforGeeks


Given a grid with each cell consisting of positive, negative or no points i.e, zero points. We
can move across a cell only if we have positive points ( > 0 ). Whenever we pass through
a cell, points in that cell are added to our overall points. We need to find minimum initial
points to reach cell (m-1, n-1) from (0, 0).
Constraints :

• From a cell (i, j) we can move to (i+1, j) or (i, j+1).


• We cannot move from (i, j) if your overall points at (i, j) is <= 0.
• We have to reach at (n-1, m-1) with minimum positive points i.e., > 0.

Input: points[m][n] = { {-2, -3, 3},


{-5, -10, 1},
{10, 30, -5}
};
Output: 7
Explanation:
7 is the minimum value to reach destination with
positive throughout the path. Below is the path.

(0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2)

We start from (0, 0) with 7, we reach(0, 1)


with 5, (0, 2) with 2, (1, 2) with 5, (2, 2)
with and finally we have 1 point (we needed
greater than 0 points at the end).

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.

dp[i][j] = max(min_Points_on_exit – points[i][j], 1)


Let us see how above expression covers all cases.

• 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).

Finally return dp[0][0] which is our answer.


Below is the implementation of above algorithm.

C++

1223
Chapter 174. Minimum Initial Points to Reach Destination

// C++ program to find minimum initial points to reach destination


#include<bits/stdc++.h>
#define R 3
#define C 3
  
using namespace std;
  
int minInitialPoints(int points[][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[R][C];
    int m = R, n = C;
  
    // Base case
    dp[m-1][n-1] = points[m-1][n-1] > 0? 1:
                   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] = max(dp[i+1][n-1] - points[i][n-1], 1);
    for (int j = n-2; j >= 0; j--)
         dp[m-1][j] = 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 = min(dp[i+1][j], dp[i][j+1]);
            dp[i][j] = max(min_points_on_exit - points[i][j], 1);
        }
     }
  
     return dp[0][0];
}
  
// Driver Program
int main()
{
  
    int points[R][C] = { {-2,-3,3},
                      {-5,-10,1},
                      {10,30,-5}
                    };
    cout << "Minimum Initial Points Required: "

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

          System.out.println("Minimum Initial Points Required: "+


                                            minInitialPoints(points,R,C) );
    }
}/* This code is contributed by Rajat Mishra */

C#

// C# program Minimum Initial Points


// to Reach Destination
using System;
class GFG {
      
    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]);

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:

Minimum Initial Points Required: 7

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

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:

Input : mat[][] = { {2, 3, 2, 1, 4},


{3, 2, 5, 8, 2},
{1, 1, 2, 2, 1} }
Output : 4
The movement and cells covered are as follows:
(0, 0)->(0, 2)
|
(2, 2)->(2, 4)

Input : mat[][] = { {2, 4, 2},


{5, 3, 8},
{1, 1, 1} }
Output : 3

1228
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

Source: Asked in Directi


Algorithm: A dynamic programming approach is given below:

C++

// C++ implementation to count minimum cells required


// to be covered to reach destination
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 100
  
// function to count minimum cells required
// to be covered to reach destination
int minCells(int mat[SIZE][SIZE], int m, int n)
{
    // to store min cells required to be
    // covered to reach a particular cell
    int dp[m][n];
  
    // initially no cells can be reached
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            dp[i][j] = INT_MAX;
  
    // base case
    dp[0][0] = 1;
  

1229
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

    // building up the dp[][] matrix


    for (int i = 0; i < m; i++) {
        for (int 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] != INT_MAX && (j + mat[i][j]) < n
                && (dp[i][j] + 1) < dp[i][j + mat[i][j]])
                dp[i][j + mat[i][j]] = dp[i][j] + 1;
  
            // the other half of the condition finds the cell
            // right below that can be reached from (i, j)
            if (dp[i][j] != INT_MAX && (i + mat[i][j]) < m
                && (dp[i][j] + 1) < dp[i + mat[i][j]][j])
                dp[i + mat[i][j]][j] = dp[i][j] + 1;
        }
    }
  
    // it true then cell (m-1, n-1) can be reached
    // from cell (0, 0) and returns the minimum
    // number of cells covered
    if (dp[m - 1][n - 1] != INT_MAX)
        return dp[m - 1][n - 1];
  
    // cell (m-1, n-1) cannot be reached from
    // cell (0, 0)
    return -1;
}
  
// Driver program to test above
int main()
{
    int mat[SIZE][SIZE] = { { 2, 3, 2, 1, 4 },
                            { 3, 2, 5, 8, 2 },
                            { 1, 1, 2, 2, 1 } };
  
    int m = 3, n = 5;
    cout << "Minimum number of cells = "
         << minCells(mat, m, n);
  
    return 0;
}

Java

// Java implementation to count minimum

1230
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

// cells required to be covered to reach


// destination
class MinCellsDestination
{
    static final int SIZE=100;
     
    // function to count minimum cells required
    // to be covered to reach destination
    static int minCells(int mat[][], int m, int n)
    {
        // to store min cells required to be
        // covered to reach a particular cell
        int dp[][] = new int[m][n];
        
        // initially no cells can be reached
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                dp[i][j] = Integer.MAX_VALUE;
        
        // base case
        dp[0][0] = 1;
        
        // building up the dp[][] matrix
        for (int i = 0; i < m; i++) {
            for (int 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] != Integer.MAX_VALUE && 
                   (j + mat[i][j]) < n && (dp[i][j] + 1)
                   < dp[i][j + mat[i][j]])
                    dp[i][j + mat[i][j]] = dp[i][j] + 1;
        
                // the other half of the condition finds
                // the cell right below that can be 
                // reached from (i, j)
                if (dp[i][j] != Integer.MAX_VALUE && 
                   (i + mat[i][j]) < m && (dp[i][j] + 1)
                   < dp[i + mat[i][j]][j])
                    dp[i + mat[i][j]][j] = dp[i][j] + 1;
            }
        }
        
        // it true then cell (m-1, n-1) can be reached
        // from cell (0, 0) and returns the minimum

1231
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

        // number of cells covered


        if (dp[m - 1][n - 1] != Integer.MAX_VALUE)
            return dp[m - 1][n - 1];
        
        // cell (m-1, n-1) cannot be reached from
        // cell (0, 0)
        return -1;
    }
      
    // Driver code
    public static void main(String args[])
    {
         int mat[][] = { { 2, 3, 2, 1, 4 },
                         { 3, 2, 5, 8, 2 },
                         { 1, 1, 2, 2, 1 }};
    
        int m = 3, n = 5;
        System.out.println("Minimum number of cells" +
                          " = " + minCells(mat, m, n));
    }
}
/* This code is contributed by Danish Kaleem */

C#

// C# implementation to count minimum


// cells required to be covered to reach
// destination
using System;
  
class GFG {
      
    //static int SIZE=100;
      
    // function to count minimum cells required
    // to be covered to reach destination
    static int minCells(int [,]mat, int m, int n)
    {
          
        // to store min cells required to be
        // covered to reach a particular cell
        int [,]dp = new int[m,n];
      
        // initially no cells can be reached
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                dp[i,j] = int.MaxValue;
      

1232
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

        // base case


        dp[0,0] = 1;
      
        // building up the dp[][] matrix
        for (int i = 0; i < m; i++) {
            for (int 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] != int.MaxValue && 
                (j + mat[i,j]) < n && (dp[i,j] + 1)
                < dp[i,j + mat[i,j]])
                    dp[i,j + mat[i,j]] = dp[i,j] + 1;
      
                // the other half of the condition
                // finds the cell right below that
                // can be reached from (i, j)
                if (dp[i,j] != int.MaxValue && 
                (i + mat[i,j]) < m && (dp[i,j] + 1)
                < dp[i + mat[i,j],j])
                    dp[i + mat[i,j],j] = dp[i,j] + 1;
            }
        }
      
        // it true then cell (m-1, n-1) can be
        // reached from cell (0, 0) and returns
        // the minimum number of cells covered
        if (dp[m - 1,n - 1] != int.MaxValue)
            return dp[m - 1,n - 1];
      
        // cell (m-1, n-1) cannot be reached from
        // cell (0, 0)
        return -1;
    }
      
    // Driver code
    public static void Main()
    {
        int [,]mat = { { 2, 3, 2, 1, 4 },
                       { 3, 2, 5, 8, 2 },
                       { 1, 1, 2, 2, 1 } };
  
        int m = 3, n = 5;
        Console.WriteLine("Minimum number of "

1233
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

            + "cells = " + minCells(mat, m, n));


    }
}
  
// This code is contributed by anuj_67.

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

                        ($j + $mat[$i][$j]) <$n


                         and ($dp[$i][$j] + 1) < 
                     $dp[$i][$j + $mat[$i][$j]])
                       
                $dp[$i][$j + $mat[$i][$j]] = 
                           $dp[$i][$j] + 1;
  
            // the other half of the 
            // condition finds the cell
            // right below that can be
            // reached from (i, j)
            if ($dp[$i][$j] != PHP_INT_MAX and 
                      ($i + $mat[$i][$j]) < $m
                      and ($dp[$i][$j] + 1) < 
                      $dp[$i +$mat[$i][$j]][$j])
                        
                $dp[$i + $mat[$i][$j]][$j] = $dp[$i][$j] + 1;
        }
    }
  
    // it true then cell 
    // (m-1, n-1) can be reached
    // from cell (0, 0) and 
    // returns the minimum
    // number of cells covered
    if ($dp[$m - 1][$n - 1] != PHP_INT_MAX)
        return $dp[$m - 1][$n - 1];
  
    // cell (m-1, n-1) cannot 
    // be reached from
    // cell (0, 0)
    return -1;
}
  
    // Driver Code
    $mat = array(array(2, 3, 2, 1, 4),
                 array(3, 2, 5, 8, 2),
                 array(1, 1, 2, 2, 1));
  
    $m = 3; $n = 5;
    echo "Minimum number of cells = "
        , minCells($mat, $m, $n);
  
// This code is contributed by anuj_67.
?>

Output:

1235
Chapter 175. Minimum cells required to reach destination with jumps equal to cell values

Minimum number of cells = 4

Time Complexity: O(m*n)


Auxiliary Space: O(m*n)
Improved By : vt_m

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

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)

Hence the output for this test case should be 3

Following is a Breadth First Search(BFS)solution of the problem:

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

2. Push the coordinates and no of jumps in a queue.


3. Pop the queue after every level of tree.
4. Add the value at cell to the coordinates while traversing right and downward direction.
5. Return no of cells touched while jumping when it reaches bottom right corner.

// C++ program to reach bottom right corner using


// minimum jumps.
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
  
// function to check coordinates are in valid range.
bool safe(int x, int y)
{
    if (x < R && y < C && x >= 0 && y >= 0)
        return true;
    return false;
}
  
// function to return minimum no of cells to reach
// bottom right cell.
int matrixJump(int M[R][C], int R1, int C1)
{
    queue<pair<int, pair<int, int> > > q;
  
    // push the no of cells and coordinates in a queue.
    q.push(make_pair(1, make_pair(R1, C1)));
  
    while (!q.empty()) {
        int x = q.front().second.first; // x coordinate
        int y = q.front().second.second; // y coordinate
        int no_of_cells = q.front().first; // no of cells
  
        q.pop();
  
        // when it reaches bottom right return no of cells
        if (x == R - 1 && y == C - 1)            
            return no_of_cells;
  
        int v = M[x][y];
  
        if (safe(x + v, y))
            q.push(make_pair(no_of_cells + 1, make_pair(x + v, y)));
  
        if (safe(x, y + v))
            q.push(make_pair(no_of_cells + 1, make_pair(x, y + v)));
    }

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:

Time Complexity : O(n)


Auxiliary Space : O(n)

Source

https://www.geeksforgeeks.org/minimum-cells-traversed-reach-corner-every-cell-represents-jumps/

1239
Chapter 177

Minimum changes needed to


make a 3*3 matrix magic square

Minimum changes needed to make a 3*3 matrix magic square - GeeksforGeeks


Given a 3*3 matrix, find the minimum number of changes that need to be made to it
in order to turn it into a magic square. A magic square is a square matrix whose sum of all
the rows are the same, the sum of all the columns are the same and the sum of both the
diagonals are the same.
Examples:

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.

There are 8 possible magic squares of 3*3 dimensions, which are

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

Minimum cost to convert 3 X 3


matrix into magic square

Minimum cost to convert 3 X 3 matrix into magic square - GeeksforGeeks


A Magic Square is a n x n matrix of distinct element from 1 to n2 where the sum of any
row, column or diagonal is always equal to same number.
Consider a 3 X 3 matrix, s, of integers in the inclusive range [1, 9] . We can convert any
digit, a, to any other digit, b, in the range [1, 9] at cost |a – b|.
Given s, convert it into a magic square at minimal cost by changing zero or more of its
digits. The task is to find minimum cost.
Note: The resulting matrix must contain distinct integers in the inclusive range [1, 9].
Examples:

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

There are two ways to approach this:


So, compute all 8 magic squares by examining all permutations of integers 1, 2, 3, ….., 9 and
for each one, check if it forms a magic square if the permutation is inserted into the square
starting from the upper left hand corner.
Below is C++ implementation of this approach:

#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

    // Checking if diagnol 2 sum is same


    tmp = 0;
    for (int i = 0; i < 3; ++i)
        tmp += a[2 - i][i];
    if (tmp != s)
        return 0;
    return 1;
}
  
// Generating all magic square
void find_magic_squares(vector<vector<int> >& magic_squares)
{
    vector<int> v(9);
  
    // Initialing the vector
    for (int i = 0; i < 9; ++i)
        v[i] = i + 1;
  
    // Producing all permutation of vector
    // and checking if it denote the magic square or not.
    do {
        if (is_magic_square(v)) {
            magic_squares.push_back(v);
        }
    } while (next_permutation(v.begin(), v.end()));
}
  
// Return sum of difference between each element of two vector
int diff(vector<int> a, vector<int> b)
{
    int res = 0;
  
    for (int i = 0; i < 9; ++i)
        res += abs(a[i] - b[i]);
  
    return res;
}
  
// Wrapper function
int wrapper(vector<int> v)
{
    int res = INT_MAX;
    vector<vector<int> > magic_squares;
  
    // generating all magic square
    find_magic_squares(magic_squares);
  
    for (int i = 0; i < magic_squares.size(); ++i) {

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

Minimum cost to sort a matrix


of numbers from 0 to n^2 – 1

Minimum cost to sort a matrix of numbers from 0 to n^2 - 1 - GeeksforGeeks


Given an n x n matrix containing all the numbers in the range 0 to n2 -1. The problem is to
calculate the total energy required for rearranging all the numbers in the matrix in strictly
increasing order, i.e., after the rearrangement the 1st row contains ‘n’ numbers from 0 to n-1,
then 2nd row from n to 2n-1 and so on up to the last or nth row. A number can be moved
in any of the four directions left, right, top or bottom from its current position to reach
its destination in the final modified matrix. The number of steps moved in transferring a
number from its current location to its required destination is the energy required by the
number for its movement. For example, in a 4 x 4 matrix, number ‘6’ is present at location
(2, 3). Its destination location in the modified matrix is (1, 1). So ‘6’ is moved 2 steps
towards left and 1 step up to reach location (1, 1). Total 3 steps moved and thus energy
required by ‘6’ is 3 units. In this way we have to sum up all the energies required in the
movement / rearrangement of all the numbers.
Examples :

Input : mat[][] = { {3, 0},


{2, 1} }
Output : 4 units
For number '3':
Move it one step right and one step down.
Total 2 steps thus energy required = 2 units.

For number '0':


Move it one step left.
Total 1 step thus energy required = 1 unit.

For number '1':

1247
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1

Move it one step up.


Total 1 step thus energy required = 1 unit.

Total energy required = 4 units.

Input : mat[][] = { {4, 7, 10, 3},


{8, 5, 6, 1},
{9, 11, 10, 2},
{15, 13, 14, 12} }
Output : 22 units

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++

// C++ implementation to find the total energy


// required to rearrange the numbers
#include <bits/stdc++.h>
  
using namespace std;
  
#define SIZE 100
  
// function to find the total energy
// required to rearrange the numbers
int calculateEnergy(int mat[SIZE][SIZE], 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

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

// Java implementation to find


// the total energy required 
// to rearrange the numbers
  
import java.util.*;
import java.lang.*;
  
public class GfG{
  
    private final static int SIZE  = 100;
   
    // function to find the total energy
    // required to rearrange the numbers

1249
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1

    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);
            }
        }
   
        // required total energy
        return tot_energy;
    }
      
    // Driver function
    public static void main(String argc[]){
  
        int[][] mat = new int[][] {{ 4, 7, 0, 3 },
                                   { 8, 5, 6, 1 },
                                   { 9, 11, 10, 2 },
                                   { 15, 13, 14, 12 }};
  
        int n = 4;
   
    System.out.println("Total energy required = "
         + calculateEnergy(mat, n) + " units");

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

# implementation to find the total


# energy required to rearrange the
# numbers
n = 4
  
# function to find the total energy
# required to rearrange the numbers
def calculateEnergy(mat,n):
  
    tot_energy = 0
  
    # nested loops to acess the 
    # elements of the given matrix
    for i in range(n):
        for j in range(n):
  
            #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
            # 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
mat = [[4, 7, 0, 3],
       [8, 5, 6, 1],

1251
Chapter 179. Minimum cost to sort a matrix of numbers from 0 to n^2 – 1

         [9, 11, 10, 2],


       [15, 13, 14, 12]]
print("Total energy required = ",
        calculateEnergy(mat,n), "units")
  
# This code is contributed by Shrikant13.

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

            // (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 += abs($i_des - $i) + 
                           abs($j_des - $j);
        }
    }
  
    // required total energy
    return $tot_energy;
}
  
// Driver Code
$mat = array(array (4, 7, 0, 3),
             array (8, 5, 6, 1),
             array (9, 11, 10, 2),
             array (15, 13, 14, 12));
$n = 4;
  
echo "Total energy required = ",
calculateEnergy($mat, $n) , " units";
  
// This code is contributed by ajit
?>

Output :

Total energy required = 22 units

Time Complexity : O(n2 )


Improved By : shrikanth13, jit_t

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

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++

// C++ program to find the minimum absolute difference


// between any of the adjacent elements of an array
// which is created by picking one element from each
// row of the matrix.
#include<bits/stdc++.h>
using namespace std;
#define R 2
#define C 2
  
// Return smallest element greater than or equal
// to the current element.
int bsearch(int low, int high, int n, int arr[])
{
    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
int mindiff(int arr[R][C], int n, int m)
{
    // Sort each row of the matrix.
    for (int i = 0; i < n; i++)
        sort(arr[i], arr[i] + m);
  
    int ans = INT_MAX;
  
    // For each matrix element
    for (int i = 0; i < n - 1; i++)

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

// Java program to find the minimum 


// absolute difference between any
// of the adjacent elements of an 
// array which is created by picking
// one element from each row of the matrix
import java.util.Arrays;
class GFG 
{
static final int R=2;
static final int C=2;
  
// Return smallest element greater than 
// or equal to the current element.
static int bsearch(int low, int high, int n, int arr[])

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

# Python program to find the minimum absolute difference


# between any of the adjacent elements of an array
# which is created by picking one element from each
# row of the matrix.
# R 2
# C 2
   
# Return smallest element greater than or equal
# to the current element.
def bsearch(low, high, n, arr):
    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
def mindiff(arr, n, m):
  
    # arr = [0 for i in range(R)][for j in range(C)]
    # Sort each row of the matrix.
    for i in range(n):
        sorted(arr)
   
    ans = 2147483647
   
    # For each matrix element
    for i in range(n-1):
        for j in range(m):
            # Search smallest element in the next row which
            # is greater than or equal to the current element

1259
Chapter 180. Minimum difference between adjacent elements of array which contain
elements from each row of a matrix

            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;
   
# Driver Program
m =[8, 5], [6, 8]
print mindiff(m, 2, 2)
  
# Contributed by: Afzal

Output:

Time Complexity : O(N*M*logM).

Source

https://www.geeksforgeeks.org/minimum-difference-adjacent-elements-array-contain-elements-row-matrix/

1260
Chapter 181

Minimum flip required to make


Binary Matrix symmetric

Minimum flip required to make Binary Matrix symmetric - GeeksforGeeks


Given a Binary Matrix of size N X N, consisting of 1s and 0s. The task is to find the
minimum flips required to make the matrix symmetric along main diagonal.
Examples :

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++

// CPP Program to find minimum flip required to make


// Binary Matrix symmetric along main diagonal
#include <bits/stdc++.h>
#define N 3
using namespace std;
  
// Return the minimum flip required to make
// Binary Matrix symmetric along main diagonal.
int minimumflip(int mat[][N], int n)
{
    int transpose[n][n];
  
    // finding the transpose of the matrix
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            transpose[i][j] = mat[j][i];
  
    // Finding the number of position where
    // element are not same.
    int flip = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            if (transpose[i][j] != mat[i][j])
                flip++;
  
    return flip / 2;
}
  
// Driver Program
int main()
{
    int n = 3;
    int mat[N][N] = {
        { 0, 0, 1 },
        { 1, 1, 1 },
        { 1, 0, 0 }
    };
    cout << minimumflip(mat, n) << endl;
    return 0;
}

Java

// Java Program to find minimum flip


// required to make Binary Matrix

1262
Chapter 181. Minimum flip required to make Binary Matrix symmetric

// symmetric along main diagonal


import java.util.*;
  
class GFG {
      
    // Return the minimum flip required
    // to make Binary Matrix symmetric
    // along main diagonal.
    static int minimumflip(int mat[][], int n)
    {
        int transpose[][] = new int[n][n];
       
        // finding the transpose of the matrix
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                transpose[i][j] = mat[j][i];
       
        // Finding the number of position 
        // where element are not same.
        int flip = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (transpose[i][j] != mat[i][j])
                    flip++;
       
        return flip / 2;
    }
      
    /* 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

# Python3 code to find minimum flip


# required to make Binary Matrix 
# symmetric along main diagonal
N = 3

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#

// C# Program to find minimum flip


// required to make Binary Matrix
// symmetric along main diagonal
using System;
  
class GFG {
      
    // Return the minimum flip required
    // to make Binary Matrix symmetric
    // along main diagonal.
    static int minimumflip(int [,]mat, int n)
    {
        int [,]transpose = new int[n,n];
      

1264
Chapter 181. Minimum flip required to make Binary Matrix symmetric

        // finding the transpose of the matrix


        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                transpose[i,j] = mat[j,i];
      
        // Finding the number of position 
        // where element are not same.
        int flip = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if (transpose[i,j] != mat[i,j])
                    flip++;
      
        return flip / 2;
    }
      
    /* Driver program to test above function */
    public static void Main() 
    {
        int n = 3;
        int [,]mat = {{ 0, 0, 1 },
                      { 1, 1, 1 },
                      { 1, 0, 0 }};
          
        Console.WriteLine(minimumflip(mat, n));
    }
}
      
// This code is contributed by vt_m. 

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

    for ( $i = 0; $i < $n; $i++)


        for ($j = 0; $j < $n; $j++)
            $transpose[$i][$j] = $mat[$j][$i];
  
    // Finding the number of 
    // position where element
    // are not same.
    $flip = 0;
    for ( $i = 0; $i < $n; $i++)
        for ( $j = 0; $j < $n; $j++)
            if ($transpose[$i][$j] != $mat[$i][$j])
                $flip++;
  
    return $flip / 2;
}
  
// Driver Code
$n = 3;
$mat = array(array(0, 0, 1),
             array(1, 1, 1),
             array(1, 0, 0));
  
echo minimumflip($mat, $n),"\n";
  
// This code is contributed by aj_36
?>

Output :

Method 2: (Efficient Approach)


The idea is to find minimum flip required to make upper triangle of matrix equals to lower
triangle of the matrix. To do so, we run two nested loop, outer loop from i = 0 to n i.e
for each row of the matrix and the inner loop from j = 0 to i, and check whether mat[i][j]
is equal to mat[j][i]. Count of number of instance where theya re not equal will be the
minimum flip required to make matrix symmetric along main diagonal.
Below is the implementation of this approach:

C++

// CPP Program to find minimum flip required to make


// Binary Matrix symmetric along main diagonal
#include <bits/stdc++.h>
#define N 3

1266
Chapter 181. Minimum flip required to make Binary Matrix symmetric

using namespace std;


  
// Return the minimum flip required to make
// Binary Matrix symmetric along main diagonal.
int minimumflip(int mat[][N], int n)
{
    // Comparing elements across diagonal
    int flip = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < i; j++)
            if (mat[i][j] != mat[j][i])
                flip++;
    return flip;
}
  
// Driver Program
int main()
{
    int n = 3;
    int mat[N][N] = {
        { 0, 0, 1 },
        { 1, 1, 1 },
        { 1, 0, 0 }
    };
    cout << minimumflip(mat, n) << endl;
    return 0;
}

Java

// Java Program to find minimum flip


// required to make Binary Matrix
// symmetric along main diagonal
import java.util.*;
  
class GFG {
      
    // Return the minimum flip required 
    // to make Binary Matrix symmetric
    // along main diagonal.
    static int minimumflip(int mat[][], int n)
    {
        // Comparing elements across diagonal
        int flip = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < i; j++)
                if (mat[i][j] != mat[j][i])
                    flip++;

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

# Python3 code 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.
def minimumflip( mat , n ):
  
    # Comparing elements across diagonal
    flip = 0
    for i in range(n):
        for j in range(i):
            if mat[i][j] != mat[j][i] :
                flip += 1
      
    return flip
  
# 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#

1268
Chapter 181. Minimum flip required to make Binary Matrix symmetric

// C# Program to find minimum flip


// required to make Binary Matrix
// symmetric along main diagonal
using System;
  
class GFG {
      
    // Return the minimum flip required 
    // to make Binary Matrix symmetric
    // along main diagonal.
    static int minimumflip(int [,]mat, int n)
    {
          
        // Comparing elements across diagonal
        int flip = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < i; j++)
                if (mat[i,j] != mat[j,i])
                    flip++;
        return flip;
    }
      
    /* Driver program to test above function */
    public static void Main() 
    {
        int n = 3;
        int [,]mat = {{ 0, 0, 1 },
                      { 1, 1, 1 },
                      { 1, 0, 0 }};
          
    Console.WriteLine(minimumflip(mat, n));
    }
}
      
// This code is contributed by vt_m. 

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

function minimumflip($mat, $n)


{
    // Comparing elements
    // across diagonal
    $flip = 0;
    for ($i = 0; $i < $n; $i++)
        for ($j = 0; $j < $i; $j++)
            if ($mat[$i][$j] != $mat[$j][$i])
                $flip++;
    return $flip;
}
  
// Driver Code
$n = 3;
$mat = array(array(0, 0, 1),
             array(1, 1, 1),
             array(1, 0, 0));
echo minimumflip($mat, $n), "\n";
      
// This code is contributed by ajit
?>

Output :

Improved By : jit_t

Source

https://www.geeksforgeeks.org/minimum-flip-required-make-binary-matrix-symmetric/

1270
Chapter 182

Minimum jumps to reach last


building in a matrix

Minimum jumps to reach last building in a matrix - GeeksforGeeks


Given a matrix containing an integer value, In which each cell of the matrix represents
height of building. Find minimum jumps needed reach from First building (0, 0) to last
(n-1, m-1). Jump from a cell to next cell is absolute difference between two building heights.
Examples :

Input : int height[][] = {{ 5, 4, 2 },


{ 9, 2, 1 },
{ 2, 5, 9 },
{ 1, 3, 11}};
Output : 12
The minimum jump path is 5 -> 2 -> 5
-> 11. Total jumps is 3 + 3 + 6 = 12.

Naive Recursive Solution:


The above problem can be solve easily by using recursion. 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 jump to
reach (m, n) can be written as “minimum jump of the 3 cells plus current jump.
Below is the implementation of the approach.
C++

// Recursive CPP program to find minimum jumps


// to reach last building from first.
#include <bits/stdc++.h>
using namespace std;
  

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

// Recursive Java program


// to find minimum jumps
// to reach last building 
// from first.
class GFG {
      
    static boolean 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 
        // if we go through 
        // diagonal
        int diag = Integer.MAX_VALUE;
          
        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 = Integer.MAX_VALUE;
          
        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 = Integer.MAX_VALUE;
          
        if (isSafe(x, y + 1))

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

Time complexity of this solution is exponential.


Dynamic Programming Solution:
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.

// A Dynamic Programming based CPP program to find


// minimum jumps to reach last building from first.
#include <bits/stdc++.h>
using namespace std;
  
#define R 4
#define C 3
  
bool isSafe(int x, int y)
{
    return (x < R && y < C);
}
  
// Lookup table used for memoization.
int dp[R][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)
{
    // if we visited it before

1277
Chapter 182. Minimum jumps to reach last building in a matrix

    if (dp[x][y] != -1)


        return dp[x][y];
  
    if (x == R - 1 && y == C - 1)
        return (dp[x][y] = 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 jump
    dp[x][y] = min({down, right, diag});
    return dp[x][y];
}
  
/* Driver program to test above functions */
int main()
{
    int height[][C] = { { 5, 4, 2 },
                       { 9, 2, 1 },
                       { 2, 5, 9 },
                       { 1, 3, 11 } };
    memset(dp, -1, sizeof(dp));
    cout << minJump(height, 0, 0);
    return 0;
}

Output:

12

Time complexity: (R*C)


Improved By : nitin mittal, vt_m

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

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++

/* C++ Program to Find minimum number of


operation required such that sum of
elements on each row and column becomes same*/
#include <bits/stdc++.h>
using namespace std;
  
// Function to find minimum operation required
// to make sum of each row and column equals
int findMinOpeartion(int matrix[][2], int n)
{
    // Initialize the sumRow[] and sumCol[]
    // array to 0
    int sumRow[n], sumCol[n];
    memset(sumRow, 0, sizeof(sumRow));
    memset(sumCol, 0, sizeof(sumCol));
  
    // Calculate sumRow[] and sumCol[] array
    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j) {
            sumRow[i] += matrix[i][j];
            sumCol[j] += matrix[i][j];
        }
  
    // Find maximum sum value in either
    // row or in column
    int maxSum = 0;
    for (int i = 0; i < n; ++i) {
        maxSum = max(maxSum, sumRow[i]);
        maxSum = max(maxSum, sumCol[i]);

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

// Java Program to Find minimum 


// number of operation required 
// such that sum of elements on 
// each row and column becomes same
import java.io.*;
  
class GFG {
  
    // Function to find minimum
    // operation required
    // to make sum of each row
    // and column equals
    static int findMinOpeartion(int matrix[][],
                                         int n)
    {
        // Initialize the sumRow[]
        // and sumCol[] array to 0
        int[] sumRow = new int[n];
        int[] sumCol = new int[n];
          
        // Calculate sumRow[] and
        // sumCol[] array
        for (int i = 0; i < n; ++i)
   
            for (int j = 0; j < n; ++j)
            {
                sumRow[i] += matrix[i][j];
                sumCol[j] += matrix[i][j];
            }
      
        // Find maximum sum value 
        // in either row or in column
        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;) 
        {

1283
Chapter 183. Minimum operations required to make each row and column of matrix equals

            // 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)
    {
        for (int i = 0; i < n; ++i) 
        {
            for (int j = 0; j < n; ++j)
                System.out.print(matrix[i][j] +
                                           " ");
           
            System.out.println();
        }
    }
  

1284
Chapter 183. Minimum operations required to make each row and column of matrix equals

    /* Driver program */


    public static void main(String[] args)
    {
        int matrix[][] = {{1, 2},
                          {3, 4}};
          
        System.out.println(findMinOpeartion(matrix, 2));
        printMatrix(matrix, 2);
  
    }
}
  
// This code is contributed by Gitanjali. 

C#

// C# Program to Find minimum 


// number of operation required 
// such that sum of elements on 
// each row and column becomes same
using System;
  
class GFG {
  
    // Function to find minimum
    // operation required
    // to make sum of each row
    // and column equals
    static int findMinOpeartion(int [,]matrix,
                                        int n)
    {
        // Initialize the sumRow[]
        // and sumCol[] array to 0
        int[] sumRow = new int[n];
        int[] sumCol = new int[n];
          
        // Calculate sumRow[] and
        // sumCol[] array
        for (int i = 0; i < n; ++i)
  
            for (int j = 0; j < n; ++j)
            {
                sumRow[i] += matrix[i,j];
                sumCol[j] += matrix[i,j];
            }
      
        // Find maximum sum value 
        // in either row or in column

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

        for (int i = 0; i < n; ++i) 


        {
            for (int j = 0; j < n; ++j)
                Console.Write(matrix[i,j] +
                                        " ");
          
            Console.WriteLine();
        }
    }
  
    /* Driver program */
    public static void Main()
    {
        int [,]matrix = {{1, 2},
                        {3, 4}};
          
        Console.WriteLine(findMinOpeartion(matrix, 2));
        printMatrix(matrix, 2);
  
    }
}
  
// This code is contributed by Vt_m. 

Output
4
4 3
3 4

Time complexity: O(n2 )


Auxiliary space: O(n)

Source

https://www.geeksforgeeks.org/minimum-operations-required-make-row-column-matrix-equals/

1287
Chapter 184

Minimum operations required


to set all elements of binary
matrix

Minimum operations required to set all elements of binary matrix - GeeksforGeeks


Given a binary matrix of N rows and M columns. The operation allowed on the matrix is
to choose any index (x, y) and toggle all the elements between the rectangle having top-left
as (0, 0) and bottom-right as (x-1, y-1). Toggling the element means changing 1 to 0 and 0
to 1. The task is to find minimum operations required to make set all the elements of the
matrix i.e make all elements as 1.
Examples:

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

order. Whenever we encounter a cell which has a value of 0, flip it.


Why traversing from end point ?
Suppose there are 0 at (x, y) and (x + 1, y + 1) cell. You shouldn’t flip a cell (x + 1, y +
1) after cell (x, y) because after you flipped (x, y) to 1, in next move to flip (x + 1, y + 1)
cell, you will flip again (x, y) to 0. So there is no benefit from the first move for flipping (x,
y) cell.
Below is implementation of this approach:

C++

// C++ program to find minimum operations required


// to set all the element of binary matrix
#include <bits/stdc++.h>
#define N 5
#define M 5
using namespace std;
  
// Return minimum operation required to make all 1s.
int minOperation(bool arr[N][M])
{
    int ans = 0;
    for (int i = N - 1; i >= 0; i--)
    {
        for (int j = M - 1; j >= 0; j--)
        {
            // check if this cell equals 0
            if(arr[i][j] == 0)
            {
                // increase the number of moves
                ans++;
  
                // flip from this cell to the start point
                for (int k = 0; k <= i; k++)
                {
                    for (int h = 0; h <= j; h++)
                    {
                        // flip the cell
                        if (arr[k][h] == 1)
                            arr[k][h] = 0;
                        else
                            arr[k][h] = 1;
                    }
                }
            }
        }
    }
    return ans;

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

# Python 3 program to find


# minimum operations required
# to set all the element of
# binary matrix
  
# Return minimum operation 
# required to make all 1s.
def minOperation(arr):
    ans = 0
    for i in range(N - 1, -1, -1):
        for j in range(M - 1, -1, -1):
              
            # check if this 
            # cell equals 0
            if(arr[i][j] == 0):
      
                # increase the
                # number of moves
                ans += 1
  
                # flip from this cell 
                # to the start point
                for k in range(i + 1):
                    for h in range(j + 1):
                      
                        # flip the cell
                        if (arr[k][h] == 1):

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:

Time Complexity: O(N2 * M2 ).


Space Complexity: O(N*M).
Improved By : ChitraNayal

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

Minimum product in a grid of


adjacent elements

Minimum product in a grid of adjacent elements - GeeksforGeeks


Given an N x M grid. The task is to find the minimum product of four adjacent numbers
in the same direction (up, down, left, right, or diagonally) in the matrix.
Examples:

Input : mat[][] = {1, 2, 3, 4,


5, 6, 7, 8,
9, 10, 11, 12}
Output : 700

2*5*7*10 gives output as 700 which is the smallest


product possible

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++

// C++ program to find the minimum product


// of adjacent elements
#include <bits/stdc++.h>
using namespace std;
const int N = 3;
const int M = 4;
  
// Function to return the minimum
// product of adjacent elements
int minimumProduct(int mat[N][M])
{
  
    // initial minimum
    int minimum = INT_MAX;
  
    // 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 than
            // the previously computed minimum
            if (p < minimum)
                minimum = p;
        }
    }
  
    return minimum;
}
  
// Driver Code
int main()
{
    int mat[][4] = { { 1, 2, 3, 4 },
                     { 4, 5, 6, 7 },
                     { 7, 8, 9, 12 } };
  
    cout << minimumProduct(mat);
    return 0;
}

Java

1295
Chapter 185. Minimum product in a grid of adjacent elements

// Java program to find 


// the minimum product
// of adjacent elements
import java.io.*;
  
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 = Integer.MAX_VALUE;
  
    // 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 
            // than the previously 
            // computed minimum
            if (p < minimum)
                minimum = p;
        }
    }
  
    return minimum;
}
  
// Driver Code
public static void main (String[] args)
{
    int mat[][] = {{1, 2, 3, 4},

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

            // than the previously 


            // computed minimum
            if (p < minimum)
                minimum = p;
        }
    }
  
    return minimum;
}
  
// Driver Code
public static void Main ()
{
    int [,]mat = {{1, 2, 3, 4},
                  {4, 5, 6, 7},
                  {7, 8, 9, 12}};
  
    Console.WriteLine(minimumProduct(mat));
}
}
  
// This code is contributed
// by anuj_67.

Output:

384

Time Complexity: O(N*M)


Improved By : vt_m

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

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.

Dry run the following code for better understanding.

// Java program to find minimum number of queens needed


// to cover a given chess board.
  
public class Backtracking {
  
    // The chessboard is represented by a 2D array.
    static boolean[][] board;
  
    // N x M is the dimension of the chess board.
    static int N, M;
  
    // The minimum number of queens required.
    // Initially, set to MAX_VAL.
    static int minCount = Integer.MAX_VALUE;
  
    static String layout; // Stores the best layout.
  
    // Driver code
    public static void main(String[] args)
    {
        N = 8;
        M = 8;
        board = new boolean[N][M];
        placeQueen(0);
  
        System.out.println(minCount);
        System.out.println("\nLayout: \n" + layout);
    }
  
    // Finds minimum count of queens needed and places them.
    static void placeQueen(int countSoFar)
    {
        int i, j;

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

        // Check the 'col'th column for any queen.


        for (i = 0; i < N; ++i)
            if (board[i][col])
                return true;
  
        // Check the 'row'th row for any queen.
        for (j = 0; j < M; ++j)
            if (board[row][j])
                return true;
  
        // Check the diagonals for any queen.
        for (i = 0; i < Math.min(N, M); ++i)
            if (row - i >= 0 && col - i >= 0 && 
                        board[row - i][col - i])
                return true;
            else if (row - i >= 0 && col + i < M &&
                           board[row - i][col + i])
                return true;
            else if (row + i < N && col - i >= 0 && 
                            board[row + i][col - i])
                return true;
            else if (row + i < N && col + i < M &&
                            board[row + i][col + i])
                return true;
  
        // This square is unattacked. Hence return 'false'.
        return false;
    }
  
    // Stores the current layout in 'layout' 
    // variable as String.
    static void storeLayout()
    {
        StringBuilder sb = new StringBuilder();
        for (boolean[] row : board) {
            for (boolean cell : row)
                sb.append(cell ? "Q " : "X ");
            sb.append("\n");
        }
        layout = sb.toString();
    }
}

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

Minimum sum submatrix in a


given 2D array

Minimum sum submatrix in a given 2D array - GeeksforGeeks


Given a 2D array, find the minimum sum submatrix in it.
Examples:

Input : M[][] = {{1, 2, -1, -4, -20},


{-8, -3, 4, 2, 1},
{3, 8, 10, 1, 3},
{-4, -1, 1, 7, -6}}
Output : -26
Submatrix starting from (Top, Left): (0, 0)
and ending at (Bottom, Right): (1, 4) indexes.
The elements are of the submtrix are:
{ {1, 2, -1, -4, -20},
{-8, -3, 4, 2, 1} } having sum = -26

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

// C++ implementation to find minimum sum 


// submatrix in a given 2D array
#include <bits/stdc++.h>
using namespace std;
  
#define ROW 4
#define COL 5
  
// Implementation of Kadane's algorithm for 
// 1D array. The function returns the miniimum 
// sum and stores starting and ending indexes
// of the minimum sum subarray at addresses
// pointed by start and finish pointers
// respectively.
int kadane(int* arr, int* start, int* finish,
                                       int n)
{
    // initialize sum, maxSum and
    int sum = 0, minSum = INT_MAX, i;
  
    // Just some initial value to check for 
    // all negative values case
    *finish = -1;
  
    // local variable
    int local_start = 0;
  
    for (i = 0; i < n; ++i) {
        sum += arr[i];
        if (sum > 0) {
            sum = 0;
            local_start = i + 1;
        } else if (sum < minSum) {
            minSum = sum;
            *start = local_start;
            *finish = i;
        }
    }
  
    // There is at-least one non-negative number
    if (*finish != -1)
        return minSum;
  
    // Special Case: When all numbers in arr[]
    // are positive
    minSum = arr[0];
    *start = *finish = 0;
  

1305
Chapter 187. Minimum sum submatrix in a given 2D array

    // Find the minimum element in array


    for (i = 1; i < n; i++) {
        if (arr[i] < minSum) {
            minSum = arr[i];
            *start = *finish = i;
        }
    }
    return minSum;
}
  
// function to find minimum sum submatrix
// in a given 2D array
void findMinSumSubmatrix(int M[][COL])
{
    // Variables to store the final output
    int minSum = INT_MAX, 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 minimum 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 minimum 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 update maxSum and other 
            // output values

1306
Chapter 187. Minimum sum submatrix in a given 2D array

            if (sum < minSum) {


                minSum = sum;
                finalLeft = left;
                finalRight = right;
                finalTop = start;
                finalBottom = finish;
            }
        }
    }
  
    // Print final values
    cout << "(Top, Left): (" << finalTop << ", " 
            << finalLeft << ")\n";
    cout << "(Bottom, Right): (" << finalBottom << ", " 
         << finalRight << ")\n";
    cout << "Minimum sum: " << minSum;
}
  
// Driver program to test above
int main()
{
    int M[ROW][COL] = { { 1, 2, -1, -4, -20 },
                        { -8, -3, 4, 2, 1 },
                        { 3, 8, 10, 1, 3 },
                        { -4, -1, 1, 7, -6 } };
    findMinSumSubmatrix(M);
    return 0;
}

Output:

(Top, Left): (0, 0)


(Bottom, Right): (1, 4)
Minimum sum: -26

Time Complexity: O(n^3)

Source

https://www.geeksforgeeks.org/minimum-sum-submatrix-given-2d-array/

1307
Chapter 188

Minimum time required to rot


all oranges

Minimum time required to rot all oranges - GeeksforGeeks


Given a matrix of dimension m*n where each cell in the matrix can have values 0, 1 or 2
which has the following meaning:

0: Empty cell

1: Cells have fresh oranges

2: Cells have rotten oranges

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:

Input: arr[][C] = { {2, 1, 0, 2, 1},


{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
Output:
All oranges can become rotten in 2 time frames.

Input: arr[][C] = { {2, 1, 0, 2, 1},


{0, 0, 1, 2, 1},

1308
Chapter 188. Minimum time required to rot all oranges

{1, 0, 0, 2, 1}};
Output:
All oranges cannot be rotten.

The idea is to user Breadth First Search. Below is algorithm.

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.

Below is implementation of the above idea.


C++

// C++ program to find minimum time required to make all


// oranges rotten
#include<bits/stdc++.h>
#define R 3
#define C 5
using namespace std;
  
// function to check whether a cell is valid / invalid
bool isvalid(int i, int j)
{
    return (i >= 0 && j >= 0 && i < R && j < C);
}
  
// structure for storing coordinates of the cell
struct ele {
    int x, y;
};
  
// Function to check whether the cell is delimiter
// which is (-1, -1)
bool isdelim(ele temp)
{
    return (temp.x == -1 && temp.y == -1);

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

        // frame so we can increase the count of the required time.


        bool flag = false;
  
        // Process all the rotten oranges in current time frame.
        while (!isdelim(Q.front()))
        {
            temp = Q.front();
  
            // Check right adjacent cell that if it can be rotten
            if (isvalid(temp.x+1, temp.y) && arr[temp.x+1][temp.y] == 1)
            {
                // if this is the first orange to get rotten, increase
                // count and set the flag.
                if (!flag) ans++, flag = true;
  
                // Make the orange rotten
                arr[temp.x+1][temp.y] = 2;
  
                // push the adjacent orange to Queue
                temp.x++;
                Q.push(temp);
  
                temp.x--; // Move back to current cell
            }
  
            // Check left adjacent cell that if it can be rotten
            if (isvalid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1) {
                if (!flag) ans++, flag = true;
                arr[temp.x-1][temp.y] = 2;
                temp.x--;
                Q.push(temp); // 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.push(temp); // 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--;

1311
Chapter 188. Minimum time required to rot all oranges

                Q.push(temp); // push this cell to Queue


            }
  
            Q.pop();
        }
  
        // Pop the delimiter
        Q.pop();
  
        // If oranges were rotten in current frame than separate the
        // rotten oranges using delimiter for the next frame for processing.
        if (!Q.empty()) {
            temp.x = -1;
            temp.y = -1;
            Q.push(temp);
        }
  
        // If Queue was empty than no rotten oranges left to process so exit
    }
  
    // Return -1 if all arranges could not rot, otherwise -1.
    return (checkall(arr))? -1: ans;
}
  
// Drive program
int main()
{
    int arr[][C] = { {2, 1, 0, 2, 1},
                     {1, 0, 1, 2, 1},
                     {1, 0, 0, 2, 1}};
    int ans = rotOranges(arr);
    if (ans == -1)
        cout << "All oranges cannot rotn";
    else
         cout << "Time required for all oranges to rot => " << ans << endl;
    return 0;
}

Java

//Java program to find minimum time required to make all


//oranges rotten
  
import java.util.LinkedList;
import java.util.Queue;
  
public class RotOrange 
{

1312
Chapter 188. Minimum time required to rot all oranges

    public final static int R = 3;


    public final static int C = 5;
      
    // structure for storing coordinates of the cell
    static class Ele
    {
        int x = 0;
        int y = 0;
        Ele(int x,int y)
        {
            this.x = x;
            this.y = y;
        }
    }
      
    // function to check whether a cell is valid / invalid
    static boolean isValid(int i, int j)
    {
        return (i >= 0 && j >= 0 && i < R && j < C);
    }
      
  
    // Function to check whether the cell is delimiter
    // which is (-1, -1)
    static boolean isDelim(Ele temp)
    {
        return (temp.x == -1 && temp.y == -1);
    }
      
    // Function to check whether there is still a fresh
    // orange remaining
    static boolean checkAll(int arr[][])
    {
         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
    static int rotOranges(int arr[][])
    {
        // Create a queue of cells
        Queue<Ele> Q=new LinkedList<>();
        Ele temp; 

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:

Time required for all oranges to rot => 2

Thanks to Gaurav Ahirwar for suggesting above solution.

Source

https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/

1316
Chapter 189

Mirror of matrix across diagonal

Mirror of matrix across diagonal - GeeksforGeeks


Given a 2-D array of order N x N, print a matrix which is mirror of given tree across diagonal.
We need to print the result in a way, swap the values of the triangle above the diagonal with
the values of the triangle below it like a mirror image swap. Print the 2-D array obtained
in matrix layout.
Examples:

Input : int mat[][] = {{1 2 4 }


{5 9 0}
{ 3 1 7}}
Output : 1 5 3
2 9 1
4 0 7

Input : mat[][] = {{1 2 3 4 }


{5 6 7 8 }
{9 10 11 12}
{13 14 15 16} }
Output : 1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

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

// Simple CPP program to find mirror of


// matrix across diagonal.
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
void imageSwap(int mat[][MAX], int n)
{
    // for diagonal which start from at 
    // first row of matrix
    int row = 0;
  
    // traverse all top right diagonal
    for (int j = 0; j < n; j++) {
  
        // here we use stack for reversing
        // the element of diagonal
        stack<int> s;
        int i = row, k = j;
        while (i < n && k >= 0) 
            s.push(mat[i++][k--]);
          
        // push all element back to matrix 
        // in reverse order
        i = row, k = j;
        while (i < n && k >= 0) {
            mat[i++][k--] = s.top();
            s.pop();
        }
    }
  
    // do the same process for all the
    // diagonal which start from last
    // column
    int column = n - 1;
    for (int j = 1; j < n; j++) {
  
        // here we use stack for reversing 
        // the elements of diagonal
        stack<int> s;
        int i = j, k = column;
        while (i < n && k >= 0) 
            s.push(mat[i++][k--]);
          
        // push all element back to matrix 
        // in reverse order
        i = j;

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

Time complexity : O(n*n)


Efficient solution of this problem is that if we observe a output matrix than we notice
that we just have to swap (mat[i][j] mat[j][i]).
Below is the implementation of above idea.\

C++

// Efficient CPP program to find mirror of

1319
Chapter 189. Mirror of matrix across diagonal

// matrix across diagonal.


#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
void imageSwap(int mat[][MAX], 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
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;
}

Java

// Efficient Java program to find mirror of


// matrix across diagonal.
import java.io.*;
  
class GFG {
      
    static int MAX = 100;

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#

// Efficient C# program to find mirror of


// matrix across diagonal.
using System;
class GFG {
      
    //static int MAX = 100;
      
    static void imageSwap(int [,]mat, int n)
    {

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

Time complexity : O(n*n)


Improved By : vt_m

1322
Chapter 189. Mirror of matrix across diagonal

Source

https://www.geeksforgeeks.org/mirror-matrix-across-diagonal/

1323
Chapter 190

Mobile Numeric Keypad


Problem

Mobile Numeric Keypad Problem - GeeksforGeeks


Given the mobile numeric keypad. You can only press buttons that are up, left, right or
down to the current button. You are not allowed to press bottom row corner buttons (i.e.
* and # ).

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)

Following is C implementation of above recursive formula.

// A Naive Recursive C program to count number of possible numbers


// of given length
#include <stdio.h>
  
// left, up, right, down move from current location
int row[] = {0, 0, -1, 0, 1};
int col[] = {0, -1, 0, 1, 0};
  
// Returns count of numbers of length n starting from key position
// (i, j) in a numeric keyboard.
int getCountUtil(char keypad[][3], int i, int j, int n)
{
    if (keypad == NULL || n <= 0)
        return 0;
  
    // From a given key, only one number is possible of length 1
    if (n == 1)
        return 1;
  
    int k=0, move=0, ro=0, co=0, totalCount = 0;
  
    // move left, up, right, down from current location and if
    // new location is valid, then get number count of length
    // (n-1) from that new position and add in count obtained so far
    for (move=0; move<5; move++)

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

   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:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

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.

// A Dynamic Programming based C program to count number of


// possible numbers of given length
#include <stdio.h>
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    if(keypad == NULL || n <= 0)
        return 0;
    if(n == 1)
        return 10;
  
    // left, up, right, down move from current location
    int row[] = {0, 0, -1, 0, 1};
    int col[] = {0, -1, 0, 1, 0};
  
    // taking n+1 for simplicity - count[i][j] will store
    // number count starting with digit i and length j
    int count[10][n+1];
    int i=0, j=0, k=0, move=0, ro=0, co=0, num = 0;
    int nextNum=0, totalCount = 0;
  
    // count numbers starting with digit i and of lengths 0 and 1
    for (i=0; i<=9; i++)
    {

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:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

A Space Optimized Solution:


The above dynamic programming approach also runs in O(n) time and requires O(n) aux-
iliary space, as only one for loop runs n times, other for loops runs for constant time. We
can see that nth iteration needs data from (n-1)th iteration only, so we need not keep the
data from older iterations. We can have a space efficient dynamic programming approach
with just two arrays of size 10. Thanks to Nik for suggesting this solution.

// A Space Optimized C program to count number of possible numbers


// of given length
#include <stdio.h>
  
// Return count of all possible numbers of length n
// in a given numeric keyboard
int getCount(char keypad[][3], int n)
{
    if(keypad == NULL || n <= 0)
        return 0;
    if(n == 1)
        return 10;
  
    // odd[i], even[i] arrays represent count of numbers starting
    // with digit i for any length j

1330
Chapter 190. Mobile Numeric Keypad Problem

    int odd[10], even[10];


    int i = 0, j = 0, useOdd = 0, totalCount = 0;
  
    for (i=0; i<=9; i++)
        odd[i] = 1;  // for j = 1
  
    for (j=2; j<=n; j++) // Bottom Up calculation from j = 2 to n
    {
        useOdd = 1 - useOdd;
  
        // Here we are explicitly writing lines for each number 0
        // to 9. But it can always be written as DFS on 4X3 grid
        // using row, column array valid moves
        if(useOdd == 1)
        {
            even[0] = odd[0] + odd[8];
            even[1] = odd[1] + odd[2] + odd[4];
            even[2] = odd[2] + odd[1] + odd[3] + odd[5];
            even[3] = odd[3] + odd[2] + odd[6];
            even[4] = odd[4] + odd[1] + odd[5] + odd[7];
            even[5] = odd[5] + odd[2] + odd[4] + odd[8] + odd[6];
            even[6] = odd[6] + odd[3] + odd[5] + odd[9];
            even[7] = odd[7] + odd[4] + odd[8];
            even[8] = odd[8] + odd[0] + odd[5] + odd[7] + odd[9];
            even[9] = odd[9] + odd[6] + odd[8];
        }
        else
        {
            odd[0] = even[0] + even[8];
            odd[1] = even[1] + even[2] + even[4];
            odd[2] = even[2] + even[1] + even[3] + even[5];
            odd[3] = even[3] + even[2] + even[6];
            odd[4] = even[4] + even[1] + even[5] + even[7];
            odd[5] = even[5] + even[2] + even[4] + even[8] + even[6];
            odd[6] = even[6] + even[3] + even[5] + even[9];
            odd[7] = even[7] + even[4] + even[8];
            odd[8] = even[8] + even[0] + even[5] + even[7] + even[9];
            odd[9] = even[9] + even[6] + even[8];
        }
    }
  
    // Get count of all possible numbers of length "n" starting
    // with digit 0, 1, 2, ..., 9
    totalCount = 0;
    if(useOdd == 1)
    {
        for (i=0; i<=9; i++)
            totalCount += even[i];

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:

Count for numbers of length 1: 10


Count for numbers of length 2: 36
Count for numbers of length 3: 138
Count for numbers of length 4: 532
Count for numbers of length 5: 2062

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

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

Below is the implementation of this approach :


C++

// CPP code to move matrix elements


// in given direction with add 
// element with same value
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 50
  
// Function to shift the matrix
// in the given direction
void moveMatrix(char d[], int n, 
                int a[MAX][MAX])
{
  
    // For right shift move.
    if (d[0] == 'r') 
    {
          
        // for each row from 
        // top to bottom
        for (int i = 0; i < n; i++) 
        {
            vector<int> v, w;
            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])
                    v.push_back(a[i][j]);

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

// Java code to move matrix 


// elements in given direction
// with add element with same value
import java.io.*;
import java.util.*;
  
class GFG
{
    // Function to shift the matrix
    // in the given direction
    static void moveMatrix(char d, 
                           int n, 
                           int a[][])
    {
      
        // For right shift move.
        if (d == 'r') 
        {
              
            // for each row from 
            // top to bottom
            for (int i = 0; i < n; i++) 
            {
                ArrayList<Integer> v = 
                               new ArrayList<Integer>();
                ArrayList<Integer> w = 
                               new ArrayList<Integer>();
                int j;
      
                // for each element of 
                // row from right to left
                for (j = n - 1; j >= 0; j--) 
                {

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

        // for up shift move


        else if (d == 'u') 
        {
            // for each column
            for (int i = 0; i < n; i++) 
            {
                ArrayList<Integer> v = 
                            new ArrayList<Integer>();
                ArrayList<Integer> w =
                            new ArrayList<Integer>();
                int j;
      
                // for each element of column
                // from top to bottom
                for (j = 0; j < n; 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 = 0;
      
                // Copying the temporary 
                // array to the current 

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#

// C# code to move matrix elements


// in given direction with add 
// element with same value
using System;
using System.Collections.Generic;
  
class GFG
{
    // Function to shift the matrix
    // in the given direction
    static void moveMatrix(char d, int n, 

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

                for (j = 0; j < n; j++)


                    a[i, j] = 0;
      
                j = 0;
  
                for (int it = 0; it < w.Count; it++)
                        a[i, j++] = w[it];
            }
        }
      
        // for down shift move.
        else if (d == 'd') 
        {
            // for each column
            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 
                // 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.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 

1348
Chapter 191. Move matrix elements in given direction and add elements with same value

                // 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.Count; it++)
                    a[j--, i] = w[it];
            }
        }
      
        // for up shift move
        else if (d == 'u') 
        {
            // for each column
            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 column
                // from top to bottom
                for (j = 0; j < n; j++) 
                {
                    // if not 0
                    if (a[j, i] != 0)
                        v.Add(a[j, i]);
                }
      
                // 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]);
                }

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

// direction with add element


// with same value
$MAX = 50;
  
// Function to shift the matrix
// in the given direction
function moveMatrix($d, $n, &$a)

    global $MAX;
      
    // For right shift move.
    if ($d[0] == 'r') 
    {
          
        // for each row from 
        // top to bottom
        for ($i = 0; $i < $n; $i++) 
        {
            $v = array();
            $w = array();
            $j = 0;
  
            // for each element of 
            // row from right to left
            for ($j = $n - 1; $j >= 0; $j--) 
            {
                // if not 0
                if ($a[$i][$j])
                    array_push($v, $a[$i][$j]);
            }
  
            // 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++;
                }
                else
                    array_push($w, $v[$j]);
            }
  

1351
Chapter 191. Move matrix elements in given direction and add elements with same value

            // 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 ($it = 0; $it != count($w); $it++)
                    $a[$i][$j--] = $w[$it];
        }
    }
  
    // for left shift move
    else if ($d[0] == 'l') 
    { 
        // for each row
        for ($i = 0; $i < $n; $i++) 
        {
            $v = array(); $w = array();
            $j = 0;
  
            // for each element of the 
            // row from left to right
            for ($j = 0; $j < $n; $j++) 
            {
                // if not 0
                if ($a[$i][$j])
                    array_push($v, 
                               $a[$i][$j]);
            }
  
            // 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++;
                }
                else

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

Multiplication of Matrix using


pthreads

Multiplication of Matrix using pthreads - GeeksforGeeks


Multiplication of matrix does take time surely. Time complexity of matrix multiplication
is O(n^3) using normal matrix multiplication. And Strassen algorithm improves it and
its time complexity is O(n^(2.8074)).
But, Is there any way to improve the performance of matrix multiplication using normal
method.
Multi-threading can be done to improve it. In multi-threading, instead of utilizing a
single core of your processor, we utilizes all or more core to solve the problem.
We create different threads, each thread evaluating some part of matrix multiplication.
Depending upon the number of cores your processor has, you can create the number of
threads required. Although you can create as many threads as you need, a better way is to
create each thread for one core.

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

Output : Multiplication of A and B


2 3 2
4 5 1
7 8 6

NOTE* It is advised to execute the program in linux based system


Compile in linux using following code:

g++ -pthread program_name.cpp

// CPP Program to multiply two matrix using pthreads


#include <bits/stdc++.h>
using namespace std;
  
// maximum size of matrix
#define MAX 4
  
// maximum number of threads
#define MAX_THREAD 4
  
int matA[MAX][MAX];
int matB[MAX][MAX];
int matC[MAX][MAX];
int step_i = 0;
  
void* multi(void* arg)
{
    int core = step_i++;
  
    // Each thread computes 1/4th of matrix multiplication
    for (int i = core * MAX / 4; i < (core + 1) * MAX / 4; i++) 

1358
Chapter 192. Multiplication of Matrix using pthreads

        for (int j = 0; j < MAX; j++) 


            for (int k = 0; k < MAX; k++) 
                matC[i][j] += matA[i][k] * matB[k][j];
}
  
// Driver Code
int main()
{
    // Generating random values in matA and matB
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) {
            matA[i][j] = rand() % 10;
            matB[i][j] = rand() % 10;
        }
    }
  
    // Displaying matA
    cout << endl
         << "Matrix A" << endl;
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) 
            cout << matA[i][j] << " ";
        cout << endl;
    }
  
    // Displaying matB
    cout << endl
         << "Matrix B" << endl;
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) 
            cout << matB[i][j] << " ";        
        cout << endl;
    }
  
    // declaring four threads
    pthread_t threads[MAX_THREAD];
  
    // Creating four threads, each evaluating its own part
    for (int i = 0; i < MAX_THREAD; i++) {
        int* p;
        pthread_create(&threads[i], NULL, multi, (void*)(p));
    }
  
    // joining and waiting for all threads to complete
    for (int i = 0; i < MAX_THREAD; i++) 
        pthread_join(threads[i], NULL);    
  
    // Displaying the result matrix

1359
Chapter 192. Multiplication of Matrix using pthreads

    cout << endl


         << "Multiplication of A and B" << endl;
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) 
            cout << matC[i][j] << " ";        
        cout << endl;
    }
    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

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

Multiplication of two Matrices


in Single line using Numpy in
Python

Multiplication of two Matrices in Single line using Numpy in Python - GeeksforGeeks


Matrix multiplication is an operation that takes two matrices as input and produces single
matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix
multiplication make sure that the number of rows of the first matrix should be equal to the
number of columns of the second matrix.
Example: Multiplication of two matrices by each other of size 3×3.

Input:matrix1 = ([1, 2, 3],


[3, 4, 5],
[7, 6, 4])
matrix2 = ([5, 2, 6],
[5, 6, 7],
[7, 6, 4])

Output : [[36 32 32]


[70 60 66]
[93 74 100]]

Methods to multiply two matrices in python


1.Using explicit for loops: This is a simple technique to multiply matrices but one of the
expensive method for larger input data set.In this, we use nested for loops to iterate each
row and each column.
If matrix1 is a n x m matrix and matrix2 is a m x l matrix.

# input two matrices of size n x m

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:

[[114 160 60]


[ 74 97 73]
[119 157 112]]

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

# We need install numpy in order to import it


import numpy as np
  
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
  
# This will return dot product
res = np.dot(mat1,mat2)
  

1362
Chapter 193. Multiplication of two Matrices in Single line using Numpy in Python

# print resulted matrix


print(res)

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

N Queen in O(n) space

N Queen in O(n) space - GeeksforGeeks


Given n, of a n x n chessboard, find the proper placement of queens on chessboard.
Previous Approach : N Queen
Algorithm :

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

// Two in the same column


// or in the same diagonal
if ((x[j] == i) or
(abs(x[j] – i) = Abs(j – k)))
then return false;

return true;
}

Algorithm nQueens(k, n) :

// Using backtracking, this procedure prints all


// possible placements of n queens on an n×n

1364
Chapter 194. N Queen in O(n) space

// chessboard so that they are nonattacking.


{
for i:= 1 to n do
{
if Place(k, i) then
{
x[k] = i;
if (k == n)
write (x[1:n]);
else
NQueens(k+1, n);
}
}
}

C++

// CPP code to for n Queen placement


#include <bits/stdc++.h>
  
#define breakLine cout << "\n---------------------------------\n";
#define MAX 10
  
using namespace std;
  
int arr[MAX], no;
  
void nQueens(int k, int n);
bool canPlace(int k, int i);
void display(int n);
  
// Function to check queens placement
void nQueens(int k, int n){
  
    for (int i = 1;i <= n;i++){
        if (canPlace(k, i)){
            arr[k] = i;
            if (k == n)
                display(n);
            else
                nQueens(k + 1, n);
        }
    }
}
  
// Helper Function to check if queen can be placed
bool canPlace(int k, int i){
    for (int j = 1;j <= k - 1;j++){

1365
Chapter 194. N Queen in O(n) space

        if (arr[j] == i || 


            (abs(arr[j] - i) == abs(j - k)))
           return false;
    }
    return true;
}
  
// Function to display placed queen
void display(int n){
    breakLine 
    cout << "Arrangement No. " << ++no;
    breakLine
  
    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++){
            if (arr[i] != j)
                cout << "\t_";
            else
                cout << "\tQ";
        }
        cout << endl;
    }
  
    breakLine
}
  
// Driver Code
int main(){
    int n = 4;    
    nQueens(1, n);    
    return 0;
}

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

N-th term of George Cantor set


of rational numbers

N-th term of George Cantor set of rational numbers - GeeksforGeeks


George cantor named mathematician gave a proof that set of rational numbers is enumerable.
We don’t have to proof it over here rather we have to determine the Nth term in the set
of rational numbers.
Examples :

Input : N = 8
Output : 2/3

Input : N = 15
Output : 1/5
See image for reference of counting.

The set of rational numbers goes like the below image :

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……

1. View this as a matrix(2-D array) with rows from 1 to n and columns


from 1 to n.
2. rows/columns will give the rational numbers.
3. Observe the pattern from the above image it will be clear how to traverse
through the matrix i.e diagonally from left to right upwards and then
from right to left downwards till we reach the Nth position.
4. There are 4 regular repeating pattern
5. After each iteration move to next number to keep counting its position using
counter k, then compare it with N

C++

// C++ program to find N-th term in


// George Cantor set of rational numbers
#include <bits/stdc++.h>
using namespace std;

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

// Java program to find N-th term in


// George Cantor set of rational number
import java.io.*;
  
class GFG 
{
    static void georgeCantor(int n)
    { 
        // let i = numerator
        int i = 1; 
          
        // let j = denominator
        int j = 1; 
          
        // to keep the check of no. of terms
        int 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++;
              
            if (k == n)
            break;
              

1371
Chapter 195. N-th term of George Cantor set of rational numbers

            // loop for traversing from left 


            // to right upwards diagonally
            while (i > 1 && k < n) {
                i--;
                j++;
                k++;
            } 
        } 
        System.out.println("N-th term : "+i +"/" +j);
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        int n = 15; 
        georgeCantor(n);
          
    }

  
// This code is contributed by vt_m

Python3

# Python3 program to find N-th term in


# George Cantor set of rational numbers
  
def georgeCantor(n):
      
    # let i = numerator
    i = 1
      
    # let j = denominator
    j = 1  
      
    # to keep the check of no. of terms
    k = 1  
          
    # loop till k is not equal to n
    while k < n:
        j += 1
        k += 1
          
        # check if k is already equal to N
        # then the first term is the
        # required rational number
        if k == n:
            break

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#

// C# program to find N-th term in


// George Cantor set of rational number
using System;
  
class GFG 
{
    static void georgeCantor(int n)
    { 
        // let i = numerator
        int i = 1; 
          
        // let j = denominator
        int j = 1; 
          

1373
Chapter 195. N-th term of George Cantor set of rational numbers

        // to keep the check of no. of terms


        int 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++;
              
            if (k == n)
            break;
              
            // loop for traversing from left 
            // to right upwards diagonally
            while (i > 1 && k < n) 
            {
                i--;
                j++;
                k++;
            } 
        } 
        Console.WriteLine("N-th term : "+i +"/" +j);
    }
      
    // Driver code
    public static void Main () 
    {

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

        if ($k == $n)


        break;
          
        // loop for traversing from left 
        // to right upwards diagonally
        while ($i > 1 && $k < $n)
        {
            $i--; $j++; $k++;
        } 
    } 
    echo "N-th term : ", $i, "/", $j;
}
  
// Driver Code
$n = 15; 
georgeCantor($n); 
  
// This code is contributed by ajit
?>

Output :

N-th term : 1/5

Improved By : jit_t

Source

https://www.geeksforgeeks.org/n-th-term-of-george-cantor-set-of-rational-numbers/

1376
Chapter 196

Nearest 1 in a binary matrix

Nearest 1 in a binary matrix - GeeksforGeeks


Given a binary matrix of order m*n, the task is to find the distance of nearest 1 for each 0
in the matrix and print final distance matrix. From any cell (i,j), we can move only in four
directions up, down, left and right.
Note : Distance from one cell to immediate another cell is always incremented by 1.
Examples:

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 :

• Take distance matrix dist[m][n] and initialize it with INT_MAX.


• Now traverse the matrix and make_pair(i,j) of inidices of cell (i, j) having value ‘1’
and push this pair into queue and update dist[i][j] = 0 because distance of ‘1’ from
itself will be always 0.
• Now pop elements from queue one by one until it gets empty and call BFS on it.
• Here we need to find the distance of nearest one and we are calling BFS for the
cells having ‘1’, so whenever we take adjacent of popped element from queue, we try
to minimize the distance by putting condition if (dist[i][j]+1) < dist[ADCi][ADCj].
Then we update the distance of adjacent element in the distance matrix and push this

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’.

// C++ program to find the minimum distance from a


// "1" in bianry matrix.
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
  
// distance matrix which stores the distnace of
// nearest '1'
int dist[MAX][MAX];
  
// Function to find the nearest '1'
void nearestOne(int mat[][MAX], int m, int n)
{
    // two array when respective values of newx and
    // newy are added to (i,j) it gives up, down,
    // left or right adjacent of (i,j) cell
    int newx[] = {-1, 0, 1, 0};
    int newy[] = {0, -1, 0, 1};
  
    // queue of pairs to store nodes for bfs
    queue< pair<int,int> > q;
  
    // traverse matrix and make pair of indices of
    // cell (i,j) having value '1' and push them
    // in queue
    for (int i=0; i<m; i++)
    {
        for (int j=0; j<n; j++)
        {
            dist[i][j] = INT_MAX;
  
            if (mat[i][j] == 1)
            {
                // distace of '1' from itself is always 0
                dist[i][j] = 0;
  
                // make pair and push it in queue
                q.push(make_pair(i, j));
            }
        }
    }
  
    // now do bfs traversal

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

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

(x-1, y+1): one step diagonal move left-up.


(x+1, y-1): one step diagonal move right-down.
(x, y+1): one step downward.
(x, y-1): one step upward.
Below is C++ implementation of this approach:

// C++ program to find number of cells a queen can move 


// with obstacles on the chessborad
#include<bits/stdc++.h>
using namespace std;
  
// Return if position is valid on chessboard
int range(int n, int x, int y)
{
  return (x <= n && x > 0 && y <= n && y > 0);
}
  
// Return the number of moves with a given direction
int check(int n, int x, int y, int xx, int yy, 
                  map <pair<int, int>, int> mp)
{
  int ans = 0;
    
  // Checking valid move of Queen in a direction.
  while (range(n, x, y) && ! mp[{x, y}])
  {
    x += xx;
    y += yy;
    ans++;
  }
    
  return ans;
}
  
// Return the number of position a Queen can move.
int numberofPosition(int n, int k, int x, int y, 
                  int obstPosx[], int obstPosy[])
{
  int x1, y1, ans = 0;
  map <pair<int, int>, int> mp;
    
  // Mapping each obstacle's position
  while(k--)
  {
    x1 = obstPosx[k];
    y1 = obstPosy[k];
      
    mp[{x1, y1}] = 1;

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 ):

• If they are horizontally at same level: abs(x1 – x2 – 1)


• If they are vertically at same level: abs(y1 – y2 – 1) is the number of free cells between.
• If they are diagonal: both abs(x1 – x2 – 1) or abs(y1 – y2 – 1) is the number of free
cells between.

1383
Chapter 197. Number of cells a queen can move with obstacles on the chessborad

Below is the implementation of this approach:

C++

// C++ program to find number of cells a queen can move


// with obstacles on the chessborad
#include <bits/stdc++.h>
using namespace std;
  
// Return the number of position a Queen can move.
int numberofPosition(int n, int k, int x, int y,
                    int obstPosx[], int obstPosy[])
{
    // d11, d12, d21, d22 are for diagnoal distances.
    // r1, r2 are for vertical distance.
    // c1, c2 are for horizontal distance.
    int d11, d12, d21, d22, r1, r2, c1, c2;
  
    // Initialise the distance to end of the board.
    d11 = min( x-1, y-1 );
    d12 = min( n-x, n-y );
    d21 = min( n-x, y-1 );
    d22 = min( x-1, n-y );
  
    r1 = y-1;
    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 = min(d11, x-obstPosx[i]-1);
  
        if ( obstPosx[i] > x && obstPosy[i] > y &&
                  obstPosx[i]-x == obstPosy[i]-y )
            d12 = min( d12, obstPosx[i]-x-1);
  
        if ( obstPosx[i] > x && y > obstPosy[i] &&
                   obstPosx[i]-x == y-obstPosy[i] )
            d21 = min(d21, obstPosx[i]-x-1);
  
        if ( x > obstPosx[i] && obstPosy[i] > y &&
                    x-obstPosx[i] == obstPosy[i]-y )

1384
Chapter 197. Number of cells a queen can move with obstacles on the chessborad

            d22 = min(d22, x-obstPosx[i]-1);


  
        if ( x == obstPosx[i] && obstPosy[i] < y )
            r1 = min(r1, y-obstPosy[i]-1);
  
        if ( x == obstPosx[i] && obstPosy[i] > y )
            r2 = min(r2, obstPosy[i]-y-1);
  
        if ( y == obstPosy[i] && obstPosx[i] < x )
            c1 = min(c1, x-obstPosx[i]-1);
  
        if ( y == obstPosy[i] && obstPosx[i] > x )
            c2 = min(c2, obstPosx[i]-x-1);
    }
  
    return d11 + d12 + d21 + d22 + r1 + r2 + c1 + c2;
}
  
// Driver code
int main(void)
{
    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);
    return 0;
}

Java

// Java program to find number of cells a 


// queen can move with obstacles on the 
// chessborad
import java.io.*;
  
class GFG {
  
    // Return the number of position a Queen
    // can move.
    static int numberofPosition(int n, int k, int x,
                 int y, int obstPosx[], int obstPosy[])
    {
          

1385
Chapter 197. Number of cells a queen can move with obstacles on the chessborad

        // d11, d12, d21, d22 are for diagnoal distances.


        // r1, r2 are for vertical distance.
        // c1, c2 are for horizontal distance.
        int d11, d12, d21, d22, r1, r2, c1, c2;
      
        // Initialise the distance to end of the board.
        d11 = Math.min( x-1, y-1 );
        d12 = Math.min( n-x, n-y );
        d21 = Math.min( n-x, y-1 );
        d22 = Math.min( x-1, n-y );
      
        r1 = y-1;
        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);

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#

// C# program to find number of cells a 


// queen can move with obstacles on the 
// chessborad
using System;
  
class GFG {
  
    // Return the number of position a Queen
    // can move.
    static int numberofPosition(int n, int k, int x,
                int y, int []obstPosx, int []obstPosy)
    {
          
        // d11, d12, d21, d22 are for diagnoal distances.
        // r1, r2 are for vertical distance.
        // c1, c2 are for horizontal distance.
        int d11, d12, d21, d22, r1, r2, c1, c2;
      
        // Initialise the distance to end of the board.
        d11 = Math.Min( x-1, y-1 );
        d12 = Math.Min( n-x, n-y );
        d21 = Math.Min( n-x, y-1 );
        d22 = Math.Min( x-1, n-y );
      
        r1 = y-1;

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

        int []obstPosx = { 3 }; // x position of obstacles


        int []obstPosy = { 5 }; // y position of obstacles
      
        Console.WriteLine(numberofPosition(n, k, Qposx,
                            Qposy, obstPosx, obstPosy));
    }
}
  
// This code is contributed by anuj_67.

Improved By : vt_m

Source

https://www.geeksforgeeks.org/number-cells-queen-can-move-obstacles-chessborad/

1389
Chapter 198

Number of days until all


chocolates become unhealthy

Number of days until all chocolates become unhealthy - GeeksforGeeks


Pablo has square chocolate Box of size n x n in which a variety of healthy chocolates are
present denoted by ‘H’ initially but he finds out that some of the chocolates are rotten and
are unhealthy denoted by ‘U’. In one day the rotten chocolates make all its neighbouring
chocolates as unhealthy. This goes on and on until all chocolates present in the chocolate
box becomes Unhealthy to eat. Find out the number of days in which the whole chocolate
box becomes Unhealthy.
(Note : It is guaranteed that atleast one of the chocolate is Unhealthy)
Examples:

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

the second day all the chocolates will


become unhealthy.

Asked in Amazon, Accolite, Arcesium.


Brute Force Approach:
Initialize a flag = 1. Use a while loop, inside that while search for an H (searching re-
quires O(n^2) time complexity if we are unable to find a H in the 2-D character array stop
incrementing the day counter and set flag as 0 to break the loop.
Below is the implementation of above approach:

// CPP program to find number of days before


// all chocolates become unhealthy.
#include <bits/stdc++.h>
using namespace std;
  
// Validates out of bounds indexing
bool isValid(int i, int j, int n)
{
    if (i < 0 || j < 0 || i >= n || j >= n)
        return false;
    return true;
}
  
// function for returning number of days
int numdays(char arr[][4], int n)
{
    int numdays = 0;
  
    while (true)
    {
        // Traverse matrix to look for unhealthy
        // chocolates and mark their neighbors.
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (arr[i][j] == 'U')
                {
  
                    if (isValid(i - 1, j - 1, n) &&
                        arr[i - 1][j - 1] == 'H')
                        arr[i - 1][j - 1] = 'V';
  
                    if (isValid(i - 1, j, n) &&
                        arr[i - 1][j] == 'H')
                        arr[i - 1][j] = 'V';
  

1391
Chapter 198. Number of days until all chocolates become unhealthy

                    if (isValid(i - 1, j + 1, n) &&


                        arr[i - 1][j + 1] == 'H')
                        arr[i - 1][j + 1] = 'V';
  
                    if (isValid(i, j - 1, n) &&
                        arr[i][j - 1] == 'H')
                        arr[i][j - 1] = 'V';
  
                    if (isValid(i, j + 1, n) &&
                        arr[i][j + 1] == 'H')
                        arr[i][j + 1] = 'V';
  
                    if (isValid(i + 1, j - 1, n) &&
                        arr[i + 1][j - 1] == 'H')
                        arr[i + 1][j - 1] = 'V';
  
                    if (isValid(i + 1, j, n) &&
                            arr[i + 1][j] == 'H')
                        arr[i + 1][j] = 'V';
  
                    if (isValid(i + 1, j + 1, n) &&
                        arr[i + 1][j + 1] == 'H')
                        arr[i + 1][j + 1] = 'V';
                }
  
                /*Here we are assigning the neighbours of U
                with the character V because we don't want
                these neighbours to be counted in that
                particular day. If we do not do so, in the
                next iteration that neighbour will also get
                counted which was supposed to be counted in
                the next day. */
            }
        }
  
        // Mark chocolates unhealthy which are made
        // unhealthy in current day.
        bool Hflag = false;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (arr[i][j] == 'V')
                {
                    arr[i][j] = 'U';
                    Hflag = true;
                }
            }

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:

number of days taken : 2

Efficient Approach (Uses BFS)


In this approach, declare a queue which inputs pairs which corresponds to the index of
the unhealthy chocolates and then as soon as the index (-1, -1) is reached we increment
the numdays counter. This Solution is basically based on calculating levels in level order
traversal (Iterative version) of a binary tree in which we push the initial indexes of the
unhealthy chocolates instead of root node and incrementing numdays instead of level counter
as soon as the index (-1, -1) is reached instead of NULL. As soon as the counter of the flag
reaches 2 we break the loop denoting that queue has encoutered two consecutive (-1, -1)
pair.
Below is the implementation of above approach:

// CPP program using Efficient approach


// to find number of days
#include <bits/stdc++.h>
using namespace std;
  

1393
Chapter 198. Number of days until all chocolates become unhealthy

// Validates out of bounds indexing


bool isValid(int i, int j, int n)
{
    if (i < 0 || j < 0 || i >= n || j >= n)
        return false;
    return true;
}
  
// function for returning number of days
int numdays(char arr[][4], int n)
{
    int numdays = 0;
    int i, j;
    queue<pair<int, int> > q;
  
    // Initializing queue with initial
    // positions of unhealthy chocolates
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++) {
            if (arr[i][j] == 'U')
                q.push(make_pair(i, j));
        }
  
    q.push(make_pair(-1, -1));
  
    // (-1, -1) is used as a checkpoint
    // to count the number of days
    pair<int, int> temp;
  
    // temporary pair to store the indexes
    int flag = 0;
    while (!q.empty()) {
        temp = q.front();
        i = temp.first;
        j = temp.second;
        q.pop();
        if (i == -1 && j == -1) {
            flag++;
            q.push(make_pair(-1, -1));
  
            // pushing the respective
           // checkpoint
            if (flag == 2)
                break;
            numdays++;
        }
        else {
            flag = 0;

1394
Chapter 198. Number of days until all chocolates become unhealthy

            if (isValid(i - 1, j - 1, n) &&


                arr[i - 1][j - 1] == 'H') {
                q.push(make_pair(i - 1, j - 1));
                arr[i - 1][j - 1] = 'U';
            }
  
            if (isValid(i - 1, j, n) &&
                arr[i - 1][j] == 'H') {
                q.push(make_pair(i - 1, j));
                arr[i - 1][j] = 'U';
            }
  
            if (isValid(i - 1, j + 1, n) &&
                arr[i - 1][j + 1] == 'H') {
                q.push(make_pair(i - 1, j + 1));
                arr[i - 1][j + 1] = 'U';
            }
  
            if (isValid(i, j - 1, n) &&
                arr[i][j - 1] == 'H') {
                q.push(make_pair(i, j - 1));
                arr[i][j - 1] = 'U';
            }
  
            if (isValid(i, j + 1, n) &&
                arr[i][j + 1] == 'H') {
                q.push(make_pair(i, j + 1));
                arr[i][j + 1] = 'U';
            }
  
            if (isValid(i + 1, j - 1, n) &&
                arr[i + 1][j - 1] == 'H') {
                q.push(make_pair(i + 1, j - 1));
                arr[i + 1][j - 1] = 'U';
            }
  
            if (isValid(i + 1, j, n) &&
                arr[i + 1][j] == 'H') {
                q.push(make_pair(i + 1, j));
                arr[i + 1][j] = 'U';
            }
  
            if (isValid(i + 1, j + 1, n) &&
                arr[i + 1][j + 1] == 'H') {
                q.push(make_pair(i + 1, j + 1));
                arr[i + 1][j + 1] = 'U';
            }
        }

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:

number of days taken : 2

Source

https://www.geeksforgeeks.org/number-of-days-until-all-chocolates-become-unhealthy/

1396
Chapter 199

Number of decisions to reach


destination

Number of decisions to reach destination - GeeksforGeeks


Given a grid which consists of 4 types of characters : ‘B’ ‘.’ ‘S’ and ‘D’. We need to reach
D starting from S, at each step we can go to neighboring cells i.e. up, down, left and right.
Cells having character ‘B’ are blocked i.e. at any step we can’t move to cell having ‘B’.
Given grid has dots in such a way that there is only one way to reach any cell
from any other cell. We need to tell how many times we need to choose our way from
more than one choices i.e. decide the path to reach D.
Examples:

Input : Grid = [".BBB.B.BB"


".....B.B."
"B.B.B.BSB"
".DB......"]
Output : 4
In above shown grid we have to decide 4
times to reach destination at (3, 7),
(3, 5), (1, 3) and (1, 1).

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

// C++ program to find decision taken to


// reach destination from source
#include <bits/stdc++.h>
using namespace std;
  
//  Utility dfs method to fill parent array
void dfs(int u, vector<int> g[], int prt[], bool visit[])
{
    visit[u] = true;
  
    //  loop over all unvisited neighbors
    for (int i = 0; i < g[u].size(); i++)
    {
        int v = g[u][i];
        if (!visit[v])
        {
            prt[v] = u;
            dfs(v, g, prt, visit);
        }
    }
}
  
// method returns decision taken to reach destination
// from source
int turnsToReachDestination(string grid[], int M)
{
    int N = grid[0].length();
  
    //  storing direction for neighbors
    int dx[] = {-1, 0, 1, 0};
    int dy[] = {0, -1, 0, 1};
  
    vector<int> g[M*N];
    bool visit[M*N] = {0};
    int prt[M*N];
    int start, dest;
  
    /*  initialize start and dest and
        store neighbours vector g
        If cell index is (i, j), then we can convert
        it to 1D as (i*N + j)  */
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (grid[i][j] == 'D')
                dest = i*N + j;
            if (grid[i][j] == 'S')

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

Number of elements greater


than modified mean in matrix

Number of elements greater than modified mean in matrix - GeeksforGeeks


Normally mean of matrix is the average of all elements present in matrix. Consider a
modified mean as floor of mean of row-wise minimum and column-wise maximum. Row-
wise minimum is the minimum element from each row of given matrix and column-wise
maximum is the maximum element from each column. Given a matrix of order n*m, find
the number of elements greater than new mean obtained.

mean = floor ( (sum(row-wise Min) + sum (col-wise Max )) /


(row_no. + col_no.) )

Examples :

Input : mat[][] = {1, 5, 6,


2, 3, 0,
5, 2, 8}
Output : 4

Input : mat[][] = {1, 5,


5, 2}
Output : 2

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++

// CPP program to count number of


// elements greater than mean
#include <bits/stdc++.h>
using namespace std;
  
// define constant for row and column
#define n 4
#define m 5
  
// function to count elements 
// greater than mean
int countElements(int mat[][m])
{
    // 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++;

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

// Java program to count


// number of elements 
// greater than mean
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;

1403
Chapter 200. Number of elements greater than modified mean in matrix

        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++;
          
        return count;
    }
      
    // driver function
    public static void main(String[] args)
    {
        int mat[][] = {{ 5, 4, 2, 8, 7}, 
                        {1, 5, 8, 3, 4},
                        {8, 5, 4, 6, 0},
                        {2, 5, 8, 9, 4}};
        System.out.println(countElements(mat));
    }
}
  
// This article is contribute by Prerna Saini.

C#

// C# program to count number of 


// elements greater than mean
using System;
  

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

    for ($i = 0; $i < $m; $i++) 


    {
        $max = $mat[0][$i];
        for ($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
    $mean = ($rowSum + $colSum) / ($m + $n);
      
    // For whole matrix count 
    // elements greater than mean
    $count = 0;
    for ($i = 0; $i < $n; $i++)
        for ($j = 0; $j < $m; $j++)
            if ($mean < $mat[$i][$j])
                $count++;
    return $count;
}
  
// Driver Code
$mat = array(array(5, 4, 2, 8, 7),
             array(1, 5, 8, 3, 4),
             array(8, 5, 4, 6, 0),
             array(2, 5, 8, 9, 4));
echo countElements($mat);
// This code is contribute by vt_m.
?>

Output:

11

Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/find-number-elements-greater-modified-mean-matrix/

1407
Chapter 201

Number of pair of positions in


matrix which are not accessible

Number of pair of positions in matrix which are not accessible - GeeksforGeeks


Given a positive integer N. Consider a matrix of N X N. No cell can be accessible from
any other cell, except the given pair cell in the form of (x1, y1), (x2, y2) i.e there is a path
(accessible) between (x2, y2) to (x1, y1). The task is to find the count of pairs (a1, b1), (a2,
b2) such that cell (a2, b2) is not accessible from (a1, b1).
Examples:

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

Below is C++ implementation of this approach:

// C++ program to count number of pair of positions


// in matrix which are not accessible
#include<bits/stdc++.h>
using namespace std;
  
// Counts number of vertices connected in a component
// containing x. Stores the count in k.
void dfs(vector<int> graph[], bool visited[],
                               int x, int *k)
{
    for (int i = 0; i < graph[x].size(); i++)
    {
        if (!visited[graph[x][i]])
        {
            // Incrementing the number of node in
            // a connected component.
            (*k)++;
  
            visited[graph[x][i]] = true;
            dfs(graph, visited, graph[x][i], k);
        }
    }
}
  
// Return the number of count of non-accessible cells.
int countNonAccessible(vector<int> graph[], int N)
{
    bool visited[N*N + N];
    memset(visited, false, sizeof(visited));
  
    int ans = 0;
    for (int i = 1; i <= N*N; i++)
    {
        if (!visited[i])
        {
            visited[i] = true;
  
            // Initialize count of connected
            // vertices found by DFS starting
            // from i.
            int k = 1;
            dfs(graph, visited, i, &k);
  
            // Update result
            ans += k * (N*N - k);
        }

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:

Time Complexity : O(N*N).

Source

https://www.geeksforgeeks.org/number-pair-positions-matrix-not-accessible/

1410
Chapter 202

Number of palindromic paths in


a matrix

Number of palindromic paths in a matrix - GeeksforGeeks


Given a matrix containing lower alphabetical characters only, we need to count number of
palindromic 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.
Examples:

Input : mat[][] = {"aaab”,


"baaa”
“abba”}
Output : 3

Number of palindromic paths are 3 from top-left to


bottom-right.
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)

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,

// C++ program to get number of palindrome


// paths in matrix
#include <bits/stdc++.h>
  
using namespace std;
  
#define R 3
#define C 4
  
// struct to represent state of recursion
// and key of map
struct cells
{
    //  indices of front cell
    int rs, cs;
  
    //  indices of end cell
    int re, ce;
    cells(int rs, int cs, int re, int ce) :
        rs(rs), cs(cs), re(re), ce(ce) { }
  
    // operator overloading to compare two
    // cells which rs needed for map
    bool operator <(const cells& other) const
    {
        return ((rs != other.rs) || (cs != other.cs) ||
               (re != other.re) || (ce != other.ce));
    }
};
  
// recursive method to return number of palindromic
// paths in matrix
// (rs, cs) ==> Indicies of current cell from a starting
//              point (First Row)
// (re, ce) ==> Indicies of current cell from a ending
//              point (Last Row)
// memo     ==> To store results of already computed
//              problems
int getPalindromicPathsRecur(char mat[R][C], int rs,
          int cs, int re, int ce, map<cells, int>& memo)
{
    // Base Case 1 : if any index rs out of boundry,

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:

Time Complexity : O(R x C)


Improved By : ImStark

Source

https://www.geeksforgeeks.org/number-of-palindromic-paths-in-a-matrix/

1414
Chapter 203

Number of paths with exactly k


coins

Number of paths with exactly k coins - GeeksforGeeks


Given a matrix where every cell has some number of coins. Count number of ways to reach
bottom right from top left with exactly k coins. We can move to (i+1, j) and (i, j+1) from
a cell (i, j).
Example:

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

The above problem can be recursively defined as below:

pathCount(m, n, k): Number of paths to reach mat[m][n] from mat[0][0]


with exactly k coins

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

Below is the implementation of above recursive algorithm.

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

# A Naive Recursive Python program to

1416
Chapter 203. Number of paths with exactly k coins

# count paths with exactly 'k' coins


  
R = 3
C = 3
  
# Recursive function to count paths
# with sum k from (0, 0) to (m, n)
def pathCountRec(mat, m, n, k):
  
    # Base cases
    if m < 0 or n < 0:
        return 0
    elif 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()
def pathCount(mat, k):
    return pathCountRec(mat, R-1, C-1, k)
  
# Driver Program
k = 12
mat = [[1, 2, 3],
       [4, 6, 5],
       [3, 2, 1]]
  
print(pathCount(mat, k))
  
# This code is contributed by Shrikant13.

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.

// A Dynamic Programming based C++ program to count paths with

1418
Chapter 203. Number of paths with exactly k coins

// exactly 'k' coins


#include <bits/stdc++.h>
#define R 3
#define C 3
#define MAX_K 1000
using namespace std;
  
int dp[R][C][MAX_K];
  
int pathCountDPRecDP(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]);
  
    // If this subproblem is already solved
    if (dp[m][n][k] != -1) return dp[m][n][k];
  
    // (m, n) can be reached either through (m-1, n) or
    // through (m, n-1)
    dp[m][n][k] = pathCountDPRecDP(mat, m-1, n, k-mat[m][n]) +
                  pathCountDPRecDP(mat, m, n-1, k-mat[m][n]);
  
    return dp[m][n][k];
}
  
// This function mainly initializes dp[][][] and calls
// pathCountDPRecDP()
int pathCountDP(int mat[][C], int k)
{
    memset(dp, -1, sizeof dp);
    return pathCountDPRecDP(mat, R-1, C-1, k);
}
  
// Driver Program to test above functions
int main()
{
    int k = 12;
    int mat[R][C] = { {1, 2, 3},
                      {4, 6, 5},
                      {3, 2, 1}
                  };
    cout << pathCountDP(mat, k);
    return 0;
}

Output:

1419
Chapter 203. Number of paths with exactly k coins

Time complexity of this solution is O(m*n*k).


Thanks to Gaurav Ahirwar for suggesting above solution.
Improved By : shrikanth13, vt_m

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

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

Lets consider element with index i, j

Row major address = B + w * (N * (i-1) + j-1)


Column major address = B + w * (M * (j-1) + i-1)

B : Base address of the array


w : Size of each element of the array

Equating both addresses, we get


B + w * (N * (i-1) + j-1) = B + w * (M * (j-1) + i-1)
N * (i-1) + j = M * (j-1) + i
N*i - N + j = M*j - M + i
M*j - j = N*i - N + M - i
(M-1) * j = N*i - N + M - i
j = (N*i - N + M - i)/(M-1) - (Eq. 1)
Similarly
i = (M*j - M + N - j)/(N-1) - (Eq. 2)

Now we have established a relation between i and j

Iterate for all possible i and find corresponding j


If j comes out to be an integer in the range 1 to N,
increment the counter.

Below is the implementation of above approach.

C++

// CPP Program to count the number


// of positions with same address
// in row major and column major order
#include <bits/stdc++.h>
  
using namespace std;
  
// Returns count of required positions
int getCount(int M, int N)
{
    int count = 0;
  
    // horizontal 1D array
    if (M == 1)
        return N;

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

// Java Program to count the number


// of positions with same address
// in row major and column major order
import java.io.*;
class GFG {
  
// Returns count of
// required positions
static int getCount(int M, int N)
{
    int count = 0;
  
    // horizontal 1D array
    if (M == 1)
        return N;
  
    // 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;
  

1424
Chapter 204. Number of positions with Same address in row major and column major
order

            // 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
    public static void main (String[] args)
    {
        int M = 3, N = 5;
        System.out.println( getCount(M, N));
    }
}
  
// This code is contributed by vt_m.

C#

// C# Program to count the number


// of positions with same address
// in row major and column major order
using System;
class GFG {
  
    // Returns count of
    // required positions
    static int getCount(int M, int N)
    {
        int count = 0;
      
        // horizontal 1D array
        if (M == 1)
            return N;
      
        // vertical 1D array
        if (N == 1)
            return M;
      
        if (N > M) {
      
            // iterating for all possible i

1425
Chapter 204. Number of positions with Same address in row major and column major
order

            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
    public static void Main ()
    {
        int M = 3, N = 5;
        Console.WriteLine( getCount(M, N));
    }
}
  
// This code is contributed by anuj_67.

PHP

<?php
// PHP Program to count the number

1426
Chapter 204. Number of positions with Same address in row major and column major
order

// of positions with same address


// in row major and column major order
  
// Returns count of required positions
function getCount( $M, $N)
{
    $count = 0;
  
    // horizontal 1D array
    if ($M == 1)
        return $N;
  
    // vertical 1D array
    if ($N == 1)
        return $M;
  
    if ($N > $M)
    {
  
        // iterating for all possible i
        for($i = 1; $i <= $M; $i++)
        {
            $numerator = $N * $i - $N + $M - $i;
            $denominator = $M - 1;
  
            // checking if j is integer
            if ($numerator % $denominator == 0) 
            {
                $j = $numerator / $denominator;
  
                // checking if j lies b/w 1 to N
                if ($j >= 1 and $j <= $N)
                    $count++;
            }
        }
    }
    else 
    {
  
        // iterating for all possible j
        for ( $j = 1; $j <= $N; $j++)
        {
            $numerator = $M * $j - $M + $N - $j;
            $denominator = $N - 1;
  
            // checking if i is integer
            if ($numerator % $denominator == 0)
            {

1427
Chapter 204. Number of positions with Same address in row major and column major
order

                $i = $numerator / $denominator;


  
                // checking if i lies b/w 1 to M
                if ($i >= 1 and $i <= $M)
                    $count++;
            }
        }
    }
    return $count;
}
  
    // Driver Code
    $M = 3; $N = 5;
    echo getCount($M, $N) ;
  
// This code is contributed by anuj_67.
?>

Output :

Time Complexity: O(M)


Complexity can be reduced to O(min(M, N)) by establishing relation of i in terms of j(Eq.
2) and iterating for all possible j in case N<M and by establishing relation j in terms of
i(Eq. 1) and iterating for all possible i otherwise.
Improved By : vt_m

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)

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 :

Output : Safe sequences are:


P2--> P4--> P1--> P3
P2--> P4--> P3--> P1
P4--> P2--> P1--> P3
P4--> P2--> P3--> P1

There are total 4 safe-sequences

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)

            // unmark the process


            marked[i] = false;
  
            // decrease the available
            for (int j = 0; j < R; j++)
                available[j] -= allocated[i][j];
        }
    }
  
    // if a safe-sequence is found, display it
    if (safe.size() == P) {
  
        total++;
        for (int i = 0; i < P; i++) {
  
            cout << "P" << safe[i] + 1;
            if (i != (P - 1))
                cout << "--> ";
        }
  
        cout << endl;
    }
}
  
// Driver Code
int main()
{
  
    // allocated matrix of size P*R
    int allocated[P][R] = { { 0, 1, 0 },
                            { 2, 0, 0 },
                            { 3, 0, 2 },
                            { 2, 1, 1 } };
  
    // max matrix of size P*R
    int max[P][R] = { { 7, 5, 3 },
                      { 3, 2, 2 },
                      { 9, 0, 2 },
                      { 2, 2, 2 } };
  
    // Initial total resources
    int resources[R] = { 10, 5, 7 };
  
    // available vector of size R
    int available[R];
  
    for (int i = 0; i < R; i++) {
  

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:

Safe sequences are:


P2--> P4--> P1--> P3
P2--> P4--> P3--> P1
P4--> P2--> P1--> P3
P4--> P2--> P3--> P1

There are total 4 safe-sequences

Source

https://www.geeksforgeeks.org/operating-system-bankers-algorithm-print-safe-state-safe-sequences/

1433
Chapter 206

Pascal Matrix

Pascal Matrix - GeeksforGeeks


In mathematics, particularly in matrix theory and combinatorics, the Pascal Matrix is
an infinite matrix containing the binomial coefficients as its elements. There are three
ways to achieve this: as either an upper-triangular matrix, a lower-triangular matrix, or a
symmetric matrix. The 5 x 5 truncations of these are shown below:

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

Below is the code to implement n x n symmetric pascal matrix:

C++

// CPP Program to print symmetric pascal matrix.


#include <bits/stdc++.h>
using namespace std;
  
// Print Pascal Matrix
void printpascalmatrix(int n)
{
    int C[2 * n + 1][2 * n + 1] = { 0 };
  
    // Calculate value of Binomial Coefficient in
    // bottom up manner
    for (int i = 0; i <= 2 * n; i++) {
        for (int 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 (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << C[i + j][i] << " ";
  
        cout << endl;
    }
}
  

1435
Chapter 206. Pascal Matrix

// Driven Program
int main()
{
    int n = 5;
    printpascalmatrix(n);
    return 0;
}

Java

// java Program to print 


// symmetric pascal matrix.
import java.io.*;
  
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++)
                System.out.print ( C[i + j][i] +" ");
                System.out.println();
          
        }
    }

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

# Python3 Program to print 


# symmetric pascal matrix.
  
# Print Pascal Matrix
def printpascalmatrix(n):
    C = [[0 for x in range(2 * n + 1)] 
            for y in range(2 * n + 1)] 
              
    # Calculate value of 
    # Binomial Coefficient
    # in ottom up manner
    for i in range(2 * n + 1):
        for j in range(min(i, 2 * n) + 1):
              
            # Base Cases
            if (j == 0 or 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 in range(n):
        for j in range(n):
            print(C[i + j][i], 
                   end = " ");
        print();
      
# Driver Code

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

Improved By : jit_t, Mithun Kumar

Source

https://www.geeksforgeeks.org/pascal-matrix/

1440
Chapter 207

Path with maximum average


value

Path with maximum average value - GeeksforGeeks


Given a square matrix of size N*N, where each cell is associated with a specific cost. A path
is defined as a specific sequence of cells which starts from top left cell move only right or
down and ends on bottom right cell. We want to find a path with maximum average over
all existing paths. Average is computed as total cost divided by number of cells visited in
path.
Examples:

Input : Matrix = [1, 2, 3


4, 5, 6
7, 8, 9]
Output : 5.8
Path with maximum average is, 1 -> 4 -> 7 -> 8 -> 9
Sum of the path is 29 and average is 29/5 = 5.8

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,

for all i, 1 <= i <= N


dp[i][0] = dp[i-1][0] + cost[i][0];
for all j, 1 <= j <= j

1441
Chapter 207. Path with maximum average value

dp[0][j] = dp[0][j-1] + cost[0][j];


otherwise
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + cost[i][j];

Once we get maximum sum of all paths we will divide this sum by (2N – 1) and we will get
our maximum average.

C++

//    C/C++ program to find maximum average cost path


#include <bits/stdc++.h>
using namespace std;
  
// Maximum number of rows and/or columns
const int M = 100;
  
// method returns maximum average of all path of
// cost matrix
double maxAverageOfPath(int cost[M][M], int N)
{
    int dp[N+1][N+1];
    dp[0][0] = cost[0][0];
  
    /* Initialize first column of total cost(dp) array */
    for (int i = 1; i < N; i++)
        dp[i][0] = dp[i-1][0] + cost[i][0];
  
    /* Initialize first row of dp array */
    for (int j = 1; j < N; j++)
        dp[0][j] = dp[0][j-1] + cost[0][j];
  
    /* Construct rest of the dp array */
    for (int i = 1; i < N; i++)
        for (int j = 1; j <= N; j++)
            dp[i][j] = max(dp[i-1][j],
                          dp[i][j-1]) + cost[i][j];
  
    // divide maximum sum by constant path
    // length : (2N - 1) for getting average
    return (double)dp[N-1][N-1] / (2*N-1);
}
  
/* Driver program to test above functions */
int main()
{
    int cost[M][M] = { {1, 2, 3},
        {6, 5, 4},

1442
Chapter 207. Path with maximum average value

        {7, 3, 9}
    };
    printf("%f", maxAverageOfPath(cost, 3));
    return 0;
}

Java

// JAVA Code for Path with maximum average


// value
class GFG {
      
    // method returns maximum average of all
    // path of cost matrix
    public static double maxAverageOfPath(int cost[][],
                                               int N)
    {
        int dp[][] = new int[N+1][N+1];
        dp[0][0] = cost[0][0];
       
        /* Initialize first column of total cost(dp)
           array */
        for (int i = 1; i < N; i++)
            dp[i][0] = dp[i-1][0] + cost[i][0];
       
        /* Initialize first row of dp array */
        for (int j = 1; j < N; j++)
            dp[0][j] = dp[0][j-1] + cost[0][j];
       
        /* Construct rest of the dp array */
        for (int i = 1; i < N; i++)
            for (int j = 1; j < N; j++)
                dp[i][j] = Math.max(dp[i-1][j],
                           dp[i][j-1]) + cost[i][j];
       
        // divide maximum sum by constant path
        // length : (2N - 1) for getting average
        return (double)dp[N-1][N-1] / (2 * N - 1);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int cost[][] = {{1, 2, 3},
                        {6, 5, 4},
                        {7, 3, 9}};
                  
        System.out.println(maxAverageOfPath(cost, 3));

1443
Chapter 207. Path with maximum average value

    }
}
// This code is contributed by Arnav Kr. Mandal.

Python3

# Python program to find 


# maximum average cost path
  
# Maximum number of rows 
# and/or columns
M = 100
  
# method returns maximum average of 
# all path of cost matrix
def maxAverageOfPath(cost, N):
      
    dp = [[0 for i in range(N + 1)] for j in range(N + 1)]
    dp[0][0] = cost[0][0]
  
    # Initialize first column of total cost(dp) array
    for i in range(1, N):
        dp[i][0] = dp[i - 1][0] + cost[i][0]
  
    # Initialize first row of dp array
    for j in range(1, N):
        dp[0][j] = dp[0][j - 1] + cost[0][j]
  
    # Construct rest of the dp array
    for i in range(1, N):
        for j in range(1, N):
            dp[i][j] = max(dp[i - 1][j],
                        dp[i][j - 1]) + cost[i][j]
  
    # divide maximum sum by costant path
    # length : (2N - 1) for getting average
    return dp[N - 1][N - 1] / (2 * N - 1)
  
# Driver program to test above function
cost = [[1, 2, 3],
        [6, 5, 4],
        [7, 3, 9]]
  
print(maxAverageOfPath(cost, 3))
  
# This code is contributed by Soumen Ghosh.

C#

1444
Chapter 207. Path with maximum average value

// C# Code for Path with maximum average


// value
using System;
class GFG {
      
    // method returns maximum average of all
    // path of cost matrix
    public static double maxAverageOfPath(int [,]cost,
                                               int N)
    {
        int [,]dp = new int[N+1,N+1];
        dp[0,0] = cost[0,0];
      
        /* Initialize first column of total cost(dp)
           array */
        for (int i = 1; i < N; i++)
            dp[i, 0] = dp[i - 1,0] + cost[i, 0];
      
        /* Initialize first row of dp array */
        for (int j = 1; j < N; j++)
            dp[0, j] = dp[0,j - 1] + cost[0, j];
      
        /* Construct rest of the dp array */
        for (int i = 1; i < N; i++)
            for (int j = 1; j < N; j++)
                dp[i, j] = Math.Max(dp[i - 1, j],
                        dp[i,j - 1]) + cost[i, j];
      
        // divide maximum sum by constant path
        // length : (2N - 1) for getting average
        return (double)dp[N - 1, N - 1] / (2 * N - 1);
    }
      
    // Driver Code
    public static void Main() 
    {
        int [,]cost = {{1, 2, 3},
                       {6, 5, 4},
                       {7, 3, 9}};
                  
        Console.Write(maxAverageOfPath(cost, 3));
    }
}
  
// This code is contributed by nitin mittal.

Output:

1445
Chapter 207. Path with maximum average value

5.2

Improved By : nitin mittal

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

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:

The run-time of row major order is -0.000526


The run-time of column major order is 0.126759

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

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].

Below is the implementation of the above approach:

// Java program to distribute n^2 numbers to n people


public class Numbers {
    public static int[][] solve(int[][] arr, int n)
    {
        // 2D array for storing the final result
        int[][] ans = new int[n][n];
  
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // using modulo to go to the firs
                // column after the last column
                ans[i][j] = arr[j][(i + j) % n];
            }
        }
        return ans;
    }
    public static void show(int[][] arr, int n)
    {
        int[][] res = solve(arr, n);
        for (int i = 0; i < n; i++) {
  
            for (int j = 0; j < n; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }
    // making a 2D array containing numbers
    public static int[][] makeArray(int n)
    {
        int[][] arr = new int[n][n];
        int c = 1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                arr[i][j] = c++;
        }
        return arr;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int n = 5;

1450
Chapter 209. Place N^2 numbers in matrix such that every row has an equal sum

        int[][] arr = makeArray(n);


        show(arr, n);
    }
}

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

Possible moves of knight

Possible moves of knight - GeeksforGeeks


Given a chess board of dimension m * n. Find number of possible moves where knight can
be moved on a chessboard from given position. If mat[i][j] = 1 then the block is filled by
something else, otherwise empty. Assume that board consist of all pieces of same color, i.e.,
there are no blocks being attacked.

Examples:

Input : mat[][] = {{1, 0, 1, 0},


{0, 1, 1, 1},
{1, 1, 0, 1},
{0, 1, 1, 1}}
pos = (2, 2)
Output : 4
Knight can moved from (2, 2) to (0, 1), (0, 3),
(1, 0) ans (3, 0).

We can observe that knight on a chessboard moves either:


1. Two moves horizontal and one move vertical
2. Two moves vertical and one move horizontal
The idea is to store all possible moves of knight and then count number of valid moves. A
move will be invalid if:
1. A block is already occupied by another piece.
2. Move is out of chessboard.
C++

// CPP program to find number of possible moves of knight


#include <bits/stdc++.h>
#define n 4

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

// Java program to find number of possible moves of knight


public class Main {

1453
Chapter 210. Possible moves of knight

public static final int n = 4;


public static final 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 program to check findPossibleMoves()
    public static void main(String[] args)
    {
        int mat[][] = { { 1, 0, 1, 0 },
                        { 0, 1, 1, 1 },
                        { 1, 1, 0, 1 },
                        { 0, 1, 1, 1 } };
  
        int p = 2, q = 2;
  
        System.out.println(findPossibleMoves(mat, p, q));
    }
}

C#

// C# program to find number of


// possible moves of knight
using System;

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

Prim’s Algorithm (Simple


Implementation for Adjacency
Matrix Representation)

Prim’s Algorithm (Simple Implementation for Adjacency Matrix Representation) - Geeks-


forGeeks
We have discussed Prim’s algorithm and its implementation for adjacency matrix represen-
tation of graphs.
As discussed in the previous post, in Prim’s algorithm, two sets are maintained, one set con-
tains list of vertices already included in MST, other set contains vertices not yet included.
In every iteration, we consider the minimum weight edge among the edges that connect the
two sets.
The implementation discussed in previous post uses two arrays to find minimum weight edge
that connects the two sets. Here we use one inMST[V]. The value of MST[i] is going to be
true if vertex i is included in the MST. In every pass, we consider only those edges such
that one vertex of the edge is included in MST and other is not. After we pick an edge, we
mark both vertices as included in MST.

// A simple C++ implementation to find minimum 


// spanning tree for adjacency representation.
#include <bits/stdc++.h>
using namespace std;
#define V 5
  
// Returns true if edge u-v is a valid edge to be
// include in MST. An edge is valid if one end is
// already included in MST and other is not in MST.
bool isValidEdge(int u, int v, vector<bool> inMST)
{

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:

Edge 0:(0, 1) cost: 2


Edge 1:(1, 2) cost: 3
Edge 2:(1, 4) cost: 5
Edge 3:(0, 3) cost: 6

Minimum cost= 16

Time Complexity : O(V3 )


Note that time complexity of previous approach that uses adjacency matrix is O(V2 ) and
time complexity of the adjacency list representation implementation is O((E+V)LogV).

Source

https://www.geeksforgeeks.org/prims-algorithm-simple-implementation-for-adjacency-matrix-representation/

1460
Chapter 212

Print K’th element in spiral


form of matrix

Print K’th element in spiral form of matrix - GeeksforGeeks


Given a 2D Matrix of order n X m , print K’th element in spiral form of matrix. See the
following examples.
Examples:

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

1. If k <= m : element is in first row.


2. Else If k <= (m+n-1) : element is in last column.
3. Else If k <= (m+n-1+m-1) : element is in last row.
4. Else If k <= (m+n-1+m-1+n-2) : element is in first column.
5. Else Element lies somewhere in middle matrix.

// C++ program for Kth element in spiral


// form of matrix
#include<bits/stdc++.h>
#define MAX 100
using namespace std;
  
/* function for Kth element */
int findK(int A[MAX][MAX], int n, int m, int k)
{
    if (n < 1 || m < 1)
        return -1;
  
    /*..........If element is in outermost ring .......*/
    /* Element is in first row */
    if (k <= m)
        return A[0][k-1];
  
    /* Element is in last column */
    if (k <= (m+n-1))
        return A[(k-m)][m-1];
  
    /* Element is in last row */
    if (k <= (m+n-1+m-1))
        return A[n-1][m-1-(k-(m+n-1))];
  
    /* Element is in first column */
    if (k <= (m+n-1+m-1+n-2))
        return A[n-1-(k-(m+n-1+m-1))][0];
  
    /*..........If element is NOT in outermost ring .......*/
    /* Recursion for sub-matrix. &A[1][1] is
       address to next inside sub matrix.*/
    return findK((int (*)[MAX])(&(A[1][1])), n-2,
                  m-2, k-(2*n+2*m-4));
}
  
/* Driver program to test above functions */
int main()
{
    int a[MAX][MAX] = {{1, 2, 3, 4, 5, 6},
                       {7, 8, 9, 10, 11, 12},
                       {13, 14, 15, 16, 17, 18}};

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

Print a given matrix in


counter-clock wise spiral form

Print a given matrix in counter-clock wise spiral form - GeeksforGeeks


Given a 2D array, print it in counter-clock wise spiral form. See the following examples.
Examples :

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

Below is the implementation :

C++

// C++ implementation to print


// the counter clock wise
// spiral traversal of matrix
#include <bits/stdc++.h>
using namespace std;
  
#define R 4
#define C 4
  
// function to print the
// required traversal
void counterClockspiralPrint(int m, 
                             int n, 
                             int arr[R][C])
{
    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
    int total = m * n;

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

// Java implementation to print


// the counter clock wise
// spiral traversal of matrix
import java.io.*;
  
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 */
  

1467
Chapter 213. Print a given matrix in counter-clock wise spiral form

        // initialize the count


        int cnt = 0;
  
        // total number of
        // elements in matrix
        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)
            {
                System.out.print(arr[i][l] + " ");
                cnt++;
            }
            l++;
  
            if (cnt == total)
                break;
  
            // Print the last row from
            // the remaining rows 
            for (i = l; i < n; ++i) 
            {
                System.out.print(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) 
                {
                    System.out.print(arr[i][n - 1] + " ");
                    cnt++;
                }
                n--;
            }
  

1468
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) 
                {
                    System.out.print(arr[k][i] + " ");
                    cnt++;
                }
                k++;
            }
        }
    }
  
// 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 } };
      
    // Function calling             
    counterClockspiralPrint(R, C, arr);
}
}
  
// This code is contributed by vt_m

Python3

# Python3 implementation to print


# the counter clock wise
# spiral traversal of matrix
R = 4
C = 4
  
# Function to print 
# the required traversal
def counterClockspiralPrint(m, n, arr) :
    k = 0; l = 0
      
    # k - starting row index
    # m - ending row index
    # l - starting column index

1469
Chapter 213. Print a given matrix in counter-clock wise spiral form

    # n - ending column index


    # i - iterator 
  
    # 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 in range(k, m) :
            print(arr[i][l], end = " ")
            cnt += 1
          
        l += 1
  
        if (cnt == total) :
            break
  
        # Print the last row from
        # the remaining rows 
        for i in range (l, n) :
            print( arr[m - 1][i], end = " ")
            cnt += 1
          
        m -= 1
          
        if (cnt == total) :
            break
  
        # Print the last column  
        # from the remaining columns 
        if (k < m) :
            for i in range(m - 1, k - 1, -1) :
                print(arr[i][n - 1], end = " ")
                cnt += 1
            n -= 1
  
        if (cnt == total) :
            break
  
        # Print the first row 

1470
Chapter 213. Print a given matrix in counter-clock wise spiral form

        # from the remaining rows 


        if (l < n) :
            for i in range(n - 1, l - 1, -1) :
                print( arr[k][i], end = " ")
                cnt += 1
                  
            k += 1
              
  
# Driver Code
arr = [ [ 1, 2, 3, 4 ],
        [ 5, 6, 7, 8 ],
        [ 9, 10, 11, 12 ],
        [ 13, 14, 15, 16 ] ]
          
counterClockspiralPrint(R, C, arr)
  
# This code is contributed by Nikita Tiwari

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

Time Complexity : O(mn).


Improved By : KRV, vt_m

Source

https://www.geeksforgeeks.org/print-given-matrix-counter-clock-wise-spiral-form/

1475
Chapter 214

Print a given matrix in reverse


spiral form

Print a given matrix in reverse spiral form - GeeksforGeeks


Given a 2D array, print it in reverse spiral form. We have already discussed Print a given
matrix in spiral form. This article discusses how to do the reverse printing. See the following
examples.

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++

// This is a modified code of


// https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
#include <iostream>
#define R 3
#define C 6
using namespace std;

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

// JAVA Code for Print a given matrix in 


// reverse spiral form
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,

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

                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)
        {
            System.out.print(b[x]+" ");
        }
    }    
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int a[][] = { {1, 2, 3, 4, 5, 6},
                    {7, 8, 9, 10, 11, 12},
                    {13, 14, 15, 16, 17, 18}};
          
        ReversespiralPrint(R, C, a);
         
    }
  }
// This code is contributed by Arnav Kr. Mandal.

C#

// C# Code for Print a given matrix in 


// reverse spiral form

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

    $a= array(array(1, 2, 3, 4, 5, 6),


              array(7, 8, 9, 10, 11, 12),
              array(13, 14, 15, 16, 17, 18));
    ReversespiralPrint($R, $C, $a);
  
// This Code is contributed by mits 
?>

Output:

11 10 9 8 7 13 14 15 16 17 18 12 6 5 4 3 2 1

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/print-given-matrix-reverse-spiral-form/

1485
Chapter 215

Print a given matrix in spiral


form

Print a given matrix in spiral form - GeeksforGeeks


Given a 2D array, print it in spiral form. See the following examples.
Examples:

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++

/* This code is adopted from the solution given 


   @ http://effprog.blogspot.com/2011/01/spiral-printing-of-two-dimensional.html */
  
#include <stdio.h>
#define R 3
#define C 6
  
void spiralPrint(int m, int n, int a[R][C])
{
    int i, 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)
    {

1487
Chapter 215. Print a given matrix in spiral form

        /* Print the first row from the remaining rows */


        for (i = l; i < n; ++i)
        {
            printf("%d ", a[k][i]);
        }
        k++;
  
        /* Print the last column from the remaining columns */
        for (i = k; i < m; ++i)
        {
            printf("%d ", a[i][n-1]);
        }
        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]);
            }
            m--;
        }
  
        /* Print the first column from the remaining columns */
        if (l < n)
        {
            for (i = m-1; i >= k; --i)
            {
                printf("%d ", a[i][l]);
            }
            l++;    
        }        
    }
}
  
/* 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}
    };
  
    spiralPrint(R, C, a);
    return 0;
}

1488
Chapter 215. Print a given matrix in spiral form

Java

// Java program to print a given matrix in spiral form


import java.io.*;
  
class GFG 
{
    // Function print matrix in spiral form
    static void spiralPrint(int m, int n, int a[][])
    {
        int i, 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)
            {
                System.out.print(a[k][i]+" ");
            }
            k++;
   
            // Print the last column from the remaining columns 
            for (i = k; i < m; ++i)
            {
                System.out.print(a[i][n-1]+" ");
            }
            n--;
   
            // Print the last row from the remaining rows */
            if ( k < m)
            {
                for (i = n-1; i >= l; --i)
                {
                    System.out.print(a[m-1][i]+" ");
                }
                m--;
            }
   
            // Print the first column from the remaining columns */
            if (l < n)
            {
                for (i = m-1; i >= k; --i)

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

# Python3 program to print 


# given matrix in spiral form
def 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 and l < n) :
          
        # Print the first row from
        # the remaining rows 
        for i in range(l, n) :
            print(a[k][i], end = " ")
              
        k += 1
  
        # Print the last column from
        # the remaining columns 

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#

// C# program to print a given


// matrix in spiral form
using System;
  
class GFG
{
    // Function print matrix in spiral form
    static void spiralPrint(int m, int n, int [,]a)
    {
        int i, k = 0, l = 0;
        /* k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index

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

                    {13, 14, 15, 16, 17, 18}


                    };
        spiralPrint(R,C,a);
    }
}
  
// This code is contributed by Sam007

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

        if ($k < $m)


        {
            for ($i = $n - 1; $i >= $l; --$i)
            {
                echo $a[$m - 1][$i] . " ";
            }
            $m--;
        }
  
        /* Print the first column from
           the remaining columns */
        if ($l < $n)
        {
            for ($i = $m - 1; $i >= $k; --$i)
            {
                echo $a[$i][$l] . " ";
            }
            $l++; 
        }     
    }
}
  
// Driver code
$a = array(array(1, 2, 3, 4, 5, 6),
           array(7, 8, 9, 10, 11, 12),
           array(13, 14, 15, 16, 17, 18));
  
spiralPrint($R, $C, $a);
  
// This code is contributed
// by ChitraNayal
?>

Output:

1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11

Time Complexity: Time complexity of the above solution is O(mn).

• Diagonal traversal of Matrix


• Print matrix in antispiral form
• Print a given matrix in zigzag form

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

Print a given matrix in zigzag


form

Print a given matrix in zigzag form - GeeksforGeeks


Given a 2D array, print it in zigzag form.
Examples :

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++

// C++ program to print


// matrix in zig-zag form
#include <iostream>
using namespace std;
  
    // Method to print matrix in zig-zag form
    void printZigZag(int row, int col, int a[][5])
    {
        int evenRow = 0; //starts from the first row
        int oddRow = 1; //starts from the next row
  
        while (evenRow<row) 
        {
            for (int i=0;i<col;i++)
            {
                // evenRow will be printed
                        // in the same direction
                cout<<a[evenRow][i] << " "; 
            }
              
            // Skipping next row so as
                // to get the next evenRow
            evenRow = evenRow + 2; 
              
            if(oddRow < row)
            {
                for (int i=col-1; i>=0; i--)
                {
                // oddRow will be printed in
                    // the opposite direction
                cout<<a[oddRow][i] << " "; 
                }
            }
          

1497
Chapter 216. Print a given matrix in zigzag form

            // Skipping next row so as 


                // to get the next oddRow
            oddRow = oddRow + 2; 
        } 
    }
  
// Driver function
int main() {
  
    int r = 3, c = 5;
  
        int mat[][5] = { {1, 2, 3, 4, 5},
                         {6, 7, 8, 9, 10},
                         {11, 12, 13, 14, 15}
                       };
  
    printZigZag(r , c , mat);
    return 0;
}
  
// This code is contributed by vt_m.

Java

// Java program to print matrix in zig-zag form


public class GFG
{
    // Method to print matrix in zig-zag form
    static void printZigZag(int row, int col, int a[][])
    {
        int evenRow = 0; // starts from the first row
        int oddRow = 1; // starts from the next row
  
        while (evenRow < row) 
        {
            for (int i = 0; i < col; i++)
            {
                // evenRow will be printed in the same direction
                System.out.print(a[evenRow][i] + " "); 
            }
              
            // Skipping next row so as to get the next evenRow
            evenRow = evenRow + 2; 
              
            if(oddRow < row)
            {
            for (int i = col - 1; i >= 0; i--)
            {

1498
Chapter 216. Print a given matrix in zigzag form

                // oddRow will be printed in the opposite direction


                System.out.print(a[oddRow][i] + " "); 
            }
            }
          
            // Skipping next row so as to get the next oddRow
            oddRow = oddRow + 2; 
        } 
    }
  
    public static void main(String[] args)
    {
  
        int r = 4, c = 5;
  
        int mat[][] = { {1, 2, 3, 4, 5},
                         {6, 7, 8, 9, 10},
                         {11, 12, 13, 14, 15}};
  
        printZigZag(r , c , mat);
    }
}

Python 3

# Python 3 program to print


# matrix in zig-zag form
  
# Method to print matrix 
# in zig-zag form
def printZigZag(row, col, a):
    evenRow = 0 # starts from the first row
    oddRow = 1 # starts from the next row
  
    while evenRow < row: 
        for i in range(col):
              
            # evenRow will be printed
            # in the same direction
            print(str(a[evenRow][i] ), 
                           end = " ")
                             
        # Skipping next row so as
        # to get the next evenRow
        evenRow = evenRow + 2
              
        if oddRow < row:
            for i in range(col - 1, -1, -1):

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#

// C# program to print matrix in zig-zag form


using System;
  
public class GFG {
      
    // Method to print matrix in zig-zag form
    static void printZigZag(int row, int col, int[, ] a)
    {
          
        // starts from the first row
        int evenRow = 0; 
          
        // starts from the next row
        int oddRow = 1; 
  
        while (evenRow < row) {
            for (int i = 0; i < col; i++) {
                  
                // evenRow will be printed in 
                // the same direction
                Console.Write(a[evenRow, i] + " ");
            }
  

1500
Chapter 216. Print a given matrix in zigzag form

            // Skipping next row so as to get the 


            // next evenRow
            evenRow = evenRow + 2;
  
            if(oddRow < row)
            {
                for (int i = col - 1; i >= 0; i--) 
                {
                  
                    // oddRow will be printed in the 
                    // opposite direction
                    Console.Write(a[oddRow, i] + " ");
                }
            }
  
            // Skipping next row so as to get 
            // the next oddRow
            oddRow = oddRow + 2;
        }
    }
  
    public static void Main()
    {
  
        int r = 3, c = 5;
          
        int[, ] 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 vt_m.

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

Time Complexity: Time complexity of the above solution is O(row*column).


Related Articles:

• Diagonal traversal of Matrix


• Print matrix in antispiral form
• Print matrix in spiral form

Improved By : jit_t, ChitraNayal

Source

https://www.geeksforgeeks.org/print-given-matrix-zigzag-form/

1503
Chapter 217

Print a matrix in Reverse Wave


Form

Print a matrix in Reverse Wave Form - GeeksforGeeks


Given a matrix, print it in Reverse Wave Form.
Examples :

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

Below is the implementation to print reverse wave form of a matrix :

C++

// C++ implementation to print


// reverse wave form of matrix
#include<bits/stdc++.h>
using namespace std;
  
#define R 4
#define C 4
  
// function to print reverse wave 
// form for a given matrix
void WavePrint(int m, int n, int arr[R][C])
{
    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

1505
Chapter 217. Print a matrix in Reverse Wave Form

            for (i = 0; i < m; i++) 


                cout << 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--) 
                cout << arr[i][j] << " ";
              
            wave = 1;
            j--;
        }
    }
}
  
// driver function
int main()
{
    int arr[R][C] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };                    
    WavePrint(R, C, arr);
      
    return 0;
}

Java

// Java implementation to print


// reverse wave form of matrix
import java.io.*;
  
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;

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

// This code is contributed by vt_m

Python3

# Python3 implementation to print


# reverse wave form of matrix
  
R = 4
C = 4
  
# function to print reverse wave 
# form for a given matrix
def wavePrint(m, n, arr):
    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 in range(m):
                print(arr[i][j], end = " "),
            wave = 0
            j -= 1
              
              
        else:
            # Print the elements of the 
            # matrix upward since the 
            # value of wave = 0
            for i in range(m - 1, -1, -1):
                print(arr[i][j], end = " "),
                  
            wave = 1
            j -= 1
  
# Driver code

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

Print a matrix in a spiral form


starting from a point

Print a matrix in a spiral form starting from a point - GeeksforGeeks


Given a matrix of size n*m, and a point P(c, r). Print the matrix in a spiral form(clockwise)
starting from the point P.
Examples :

Input : mat[][] = {{1 2 3},


{4 5 6},
{7 8 9}}
Point P = (0, 2)
Output : 3 6 5 2 9 8 7 4 1
The starting point is top left which
is 3.

This problem is mainly an extension ofprint a matrix in spiral form.


C++

// C++ program to print a matrix in spiral


// form.
#include <iostream>
using namespace std;
  
const int MAX = 100;
  
void printSpiral(int mat[][MAX], int r, int c)
{
  

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

// Java program to print a


// matrix in spiral form
import java.io.*;
  
class GFG {

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

// This code is contributed by vt_m.

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

Improved By : vt_m, jit_t

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)

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[][2] = {{1, 2}


{2, 3}};
Output : 1 2 3 2

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++

// C++ program to print matrix in alternate manner


#include<bits/stdc++.h>
using namespace std;
#define R 3

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

Time Complexity : O(R*C)


Space Complexity : O(1)
Improved By : jit_t

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

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:

Input: mat[][] = { {10, 20, 30, 40},


{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};

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

#define INF INT_MAX


#define N 4
  
// A utility function to youngify a Young Tableau.  This is different
// from standard youngify.  It assumes that the value at mat[0][0] is 
// infinite.
void youngify(int mat[][N], int i, int j)
{
    // Find the values at down and right sides of mat[i][j]
    int downVal  = (i+1 < N)? mat[i+1][j]: INF;
    int rightVal = (j+1 < N)? mat[i][j+1]: INF;
  
    // If mat[i][j] is the down right corner element, return
    if (downVal==INF && rightVal==INF)
        return;
  
    // Move the smaller of two values (downVal and rightVal) to 
    // mat[i][j] and recur for smaller value
    if (downVal < rightVal)
    {
        mat[i][j] = downVal;
        mat[i+1][j] = INF;
        youngify(mat, i+1, j);
    }
    else
    {
        mat[i][j] = rightVal;
        mat[i][j+1] = INF;
        youngify(mat, i, j+1);
    }
}
  
// A utility function to extract minimum element from Young tableau
int extractMin(int mat[][N])
{
    int ret = mat[0][0];
    mat[0][0] = INF;
    youngify(mat, 0, 0);
    return ret;
}
  
// This function uses extractMin() to print elements in sorted order
void printSorted(int mat[][N])
{
   cout << "Elements of matrix in sorted order n";
   for (int i=0; i<N*N; i++)
     cout << extractMin(mat) << " ";
}

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:

Elements of matrix in sorted order


10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50

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

        // root of heap. The next element belongs to same


        // array as the current root.
        if (root.j < N)
        {
            root.element = mat[root.i][root.j];
            root.j += 1;
        }
        // If root was the last element of its array
        else root.element =  INT_MAX; //INT_MAX is for infinite
  
        // Replace root with next element of array
        hp.replaceMin(root);
    }
}
  
// FOLLOWING ARE IMPLEMENTATIONS OF STANDARD MIN HEAP METHODS
// FROM CORMEN BOOK
// Constructor: Builds a heap from a given array a[] of given size
MinHeap::MinHeap(MinHeapNode a[], int size)
{
    heap_size = size;
    harr = a;  // store address of array
    int i = (heap_size - 1)/2;
    while (i >= 0)
    {
        MinHeapify(i);
        i--;
    }
}
  
// A recursive method to heapify a subtree with root at given index
// This method assumes that the subtrees are already heapified
void MinHeap::MinHeapify(int i)
{
    int l = left(i);
    int r = right(i);
    int smallest = i;
    if (l < heap_size && harr[l].element < harr[i].element)
        smallest = l;
    if (r < heap_size && harr[r].element < harr[smallest].element)
        smallest = r;
    if (smallest != i)
    {
        swap(&harr[i], &harr[smallest]);
        MinHeapify(smallest);
    }
}
  

1526
Chapter 220. Print all elements in sorted order from row and column wise sorted matrix

// A utility function to swap two elements


void swap(MinHeapNode *x, MinHeapNode *y)
{
    MinHeapNode temp = *x;  *x = *y;  *y = temp;
}
  
// 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:

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

Print all n digit patterns formed


by mobile Keypad

Print all n digit patterns formed by mobile Keypad - GeeksforGeeks


Given a number n. we need to print all N digit pattern formed by mobile Keypad.
Note: we can move up, down, left, right from any key of mobile keypad and every pattern
contain unique key.

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).

PrintPattern Function (DFS Function)


Add current key to pattern
Pattern += Keypad[x][y]
.... make current key as visited
visited[x][y] = true;
... Print pattern if size of Pattern == N
Call DFS for all 4 adjacent keypad key
__DFS_function

Below c++ implementation of above idea

// C++ program to print all n digit patterns


// formed by mobile keypad.
#include <bits/stdc++.h>
using namespace std;
  
// A function to check if a given cell (row, col)
// can be included in DFS
bool isSafe(int x, int y, bool Visited[][3])
{
    // row number is in range, column number 
    // is in range and not yet visited
    return (x >= 0 && x < 4 && y >= 0 && 
            y < 3 && !Visited[x][y]);
}
  
// A utility function to do DFS for a mobile Keypad
// matrix. It only considers the 4 neighbors as
// adjacent vertice and print pattern of size n
void DFS(bool visited[][3], int Keypad[][3], int n,
         string pattern, int x, int y)

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

// Drive program to test above function.


int main()
{
    int Keypad[4][3] = { { 1, 2, 3 },
                         { 4, 5, 6 },
                         { 7, 8, 9 },
                         { -1, 0, -1 } };
    int n = 3;
    patternOfSizeK(Keypad, n);
    return 0;
}

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

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.

Input : mat[][] = {"aaab”,


"baaa”
“abba”}
Output :aaaaaa, aaaaaa, abaaba

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)

Order of elements in the output array doesn’t matter.


The idea is simple. We start from top left (0, 0) and explore all paths to bottom right. If a
path turns to be palindrome, we print it.

// Java program to print all palindromic paths

1532
Chapter 222. Print all palindromic paths from top left to bottom right in a matrix

// from top left to bottom right in a grid.


public class PalinPath {
    public static boolean isPalin(String str)
    {
        int len = str.length() / 2;
        for (int i = 0; i < len; i++) {
            if (str.charAt(i) != str.charAt(str.length() - i - 1))
                return false;
        }
        return true;
    }
  
    // i and j are row and column indexes of current cell 
    // (initially these are 0 and 0).
    public static void palindromicPath(String str, char a[][],
                                 int i, int j, int m, int n)
    {
            
        // If we have not reached bottom right corner, keep
        // exlporing
        if (j < m - 1 || i < n - 1) {
          if (i < n - 1)
             palindromicPath(str + a[i][j], a, i + 1, j, m, n);
         if (j < m - 1)
             palindromicPath(str + a[i][j], a, i, j + 1, m, n);
        } 
  
        // If we reach bottom right corner, we check if
        // if the path used is palindrome or not.
        else {
            str = str + a[n - 1][m - 1];
            if (isPalin(str))
                System.out.println(str);
        }
    }
  
    // Driver code 
    public static void main(String args[])
    {
        char arr[][] = { { 'a', 'a', 'a', 'b' },
                         { 'b', 'a', 'a', 'a' },
                         { 'a', 'b', 'b', 'a' } };
        String str = "";
        palindromicPath(str, arr, 0, 0, 4, 3);
    }
}

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

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.

// CPP program to Print all possible paths from 


// top left to bottom right of a mXn matrix
#include<iostream>
  

1535
Chapter 223. Print all possible paths from top left to bottom right of a mXn matrix

using namespace std;


  
/* mat:  Pointer to the starting of mXn matrix
   i, j: Current position of the robot (For the first call use 0,0)
   m, n: Dimentions of given the matrix
   pi:   Next index to be filed in path array
   *path[0..pi-1]: The path traversed by robot till now (Array to hold the
                  path need to have space for at least m+n elements) */
void printAllPathsUtil(int *mat, int i, int j, int m, int n, int *path, int pi)
{
    // Reached the bottom of the matrix so we are left with
    // only option to move right
    if (i == m - 1)
    {
        for (int k = j; k < n; k++)
            path[pi + k - j] = *((mat + i*n) + k);
        for (int l = 0; l < pi + n - j; l++)
            cout << path[l] << " ";
        cout << endl;
        return;
    }
  
    // Reached the right corner of the matrix we are left with
    // only the downward movement.
    if (j == n - 1)
    {
        for (int k = i; k < m; k++)
            path[pi + k - i] = *((mat + k*n) + j);
        for (int l = 0; l < pi + m - i; l++)
            cout << path[l] << " ";
        cout << endl;
        return;
    }
  
    // Add the current cell to the path being generated
    path[pi] = *((mat + i*n) + j);
  
    // Print all the paths that are possible after moving down
    printAllPathsUtil(mat, i+1, j, m, n, path, pi + 1);
  
    // Print all the paths that are possible after moving right
    printAllPathsUtil(mat, i, j+1, m, n, path, pi + 1);
  
    // Print all the paths that are possible after moving diagonal
    // printAllPathsUtil(mat, i+1, j+1, m, n, path, pi + 1);
}
  
// The main function that prints all paths from top left to bottom right

1536
Chapter 223. Print all possible paths from top left to bottom right of a mXn matrix

// in a matrix 'mat' of size mXn


void printAllPaths(int *mat, int m, int n)
{
    int *path = new int[m+n];
    printAllPathsUtil(mat, 0, 0, m, n, path, 0);
}
  
// Driver program to test abve functions
int main()
{
    int mat[2][3] = { {1, 2, 3}, {4, 5, 6} };
    printAllPaths(*mat, 2, 3);
    return 0;
}

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

# Python3 program to Print all possible paths from 


# top left to bottom right of a mXn matrix
allPaths = []
def findPaths(maze,m,n):
    path = [0 for d in range(m+n-1)]
    findPathsUtil(maze,m,n,0,0,path,0)
      
def findPathsUtil(maze,m,n,i,j,path,indx):
    global allPaths
    # if we reach the bottom of maze, we can only move right
    if i==m-1:
        for k in range(j,n):
            #path.append(maze[i][k])
            path[indx+k-j] = maze[i][k]
        # if we hit this block, it means one path is completed. 
        # Add it to paths list and print

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

Print cells with same


rectangular sums in a matrix

Print cells with same rectangular sums in a matrix - GeeksforGeeks


Given a matrix of m x n matrix, we need to print all those cells at which sum of sub-matrix
ended at this cell and sub-matrix starting at this cell is equal to remaining elements. For
better understanding please see below diagram,
Examples :

Input : mat[][] = {1, 2, 3, 5,


4, 1, 0, 2,
0, 1, 2, 0,
7, 1, 1, 0};
Output : (1, 1), (2, 2)

In above matrix, cell (1, 1) and cell (2, 2)


are our required cells because,
For cell (1, 1), sum of red and green areas is same
1+2+4+1+0+2+1+2+0+1+1+0 = 3+5+0+7
Same is true for cell (2, 2)
1+2+3+4+1+0+0+1+2+0+1+0 = 5+2+7+1

We need to print all blue boundary cells for


which sum of red area is equal to green area.

First we construct auxiliary sub-matrices similar to the linked article.


We construct two matrices sum[][] and sumr[][] such that sum[i][j] denotes sum of sub-
matrix from mat[0][0] to mat[i][j]. And sumr for storing sum till last indices i.e. sumr[i][j]

1539
Chapter 224. Print cells with same rectangular sums in a matrix

denotes sum of sub-matrix, mat[i][j] to mat[m – 1][n – 1].


Now we can use above matrices for solving this problem, red area shown in above diagram
can be calculated by adding corresponding cells from sum and sumr matrices, as mat[i][j] is
considered twice while calculating this sum we will subtract it once to get sum of red area.
Getting sum of remaining element, the green part, is pretty easy, we will just subtract sum
of red part from total sum of given matrix.
So to check whether a particular cell satisfies the given condition we will calculate the sum
of red part as explained above and compare it with total sum of matrix, if this sum is half
of total sum, current cell satisfies the condition and hence a candidate for result.
C/C++

// C++ program to print cells with same rectangular


// sum diagonally
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
  
// Method prints cell index at which rectangular sum is
// same at prime diagonal and other diagonal
void printCellWithSameRectangularArea(int mat[R][C],
                                     int m, int n)
{
    /* sum[i][j] denotes sum of sub-matrix, mat[0][0]
       to mat[i][j]
       sumr[i][j] denotes sum of sub-matrix, mat[i][j]
       to mat[m - 1][n - 1]  */
    int sum[m][n], sumr[m][n];
  
    //  Initialize both sum matrices by mat
    int totalSum = 0;
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            sumr[i][j] = sum[i][j] = mat[i][j];
            totalSum += mat[i][j];
        }
    }
  
    //  updating first and last row separately
    for (int i = 1; i < m; i++)
    {
        sum[i][0] += sum[i-1][0];
        sumr[m-i-1][n-1] += sumr[m-i][n-1];
    }
  
    //  updating first and last column separately

1540
Chapter 224. Print cells with same rectangular sums in a matrix

    for (int j = 1; j < n; j++)


    {
        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 (int i = 1; i < m; i++)
    {
        for (int j = 1; j < n; j++)
        {
            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
    /*
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cout << sum[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                cout << sumr[i][j] << " ";
            }
            cout << endl;
        }
        cout << endl;    */
  
    /* 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] -

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

// Java program to print cells with 


// same rectangular sum diagonally
  
class GFG {
      
static final int R = 4;
static final int C = 4;
  
// Method prints cell index at which 
// rectangular sum is same at 
// prime diagonal and other diagonal
static void printCellWithSameRectangularArea(int mat[][], 
                                             int m, int n) 
{
    /* sum[i][j] denotes sum of sub-matrix, mat[0][0]
    to mat[i][j]
    sumr[i][j] denotes sum of sub-matrix, mat[i][j]
    to mat[m - 1][n - 1] */
    int sum[][] = new int[m][n];
    int sumr[][] = new int[m][n];
  
    // Initialize both sum matrices by mat
    int totalSum = 0;

1542
Chapter 224. Print cells with same rectangular sums in a matrix

    for (int i = 0; i < m; i++) {


    for (int j = 0; j < n; j++) {
        sumr[i][j] = sum[i][j] = mat[i][j];
        totalSum += mat[i][j];
    }
    }
  
    // updating first and last row separately
    for (int i = 1; i < m; i++) {
    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 (int j = 1; j < n; j++) {
    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 (int i = 1; i < m; i++) {
    for (int j = 1; j < n; j++) {
        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
    /*
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print( sum[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print(sumr[i][j] + " ");
            }

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

# Python program to print cells with same rectangular


# sum diagonally
# R 4
# C 4
   
# Method prints cell index at which rectangular sum is
# same at prime diagonal and other diagonal
def printCellWithSameRectangularArea(mat, m, n):
    # sum[i][j] denotes sum of sub-matrix, mat[0][0]
    #  to mat[i][j]
    # sumr[i][j] denotes sum of sub-matrix, mat[i][j]
    # to mat[m - 1][n - 1]  
    sum = [[0 for i in range(m)]for j in range(n)]
    sumr = [[0 for i in range(m)]for j in range(n)]
   
    #  Initialize both sum matrices by mat

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

// C# program to print cells with 


// same rectangular sum diagonally
using System;
  
class GFG {
      
static int R = 4;
static int C = 4;
  
// Method prints cell index at which 
// rectangular sum is same at 
// prime diagonal and other diagonal
static void printCellWithSameRectangularArea(int [,]mat, 
                                             int m, int n) 
{
    /* sum[i][j] denotes sum of sub-
       matrix, mat[0][0] to mat[i][j]
       sumr[i][j] denotes sum of sub-matrix,
       mat[i][j] to mat[m - 1][n - 1] */
    int [,]sum = new int[m, n];
    int [,]sumr = new int[m, n];
  
    // Initialize both sum matrices by mat
    int totalSum = 0;
    for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        sumr[i, j] = sum[i, j] = mat[i, j];
        totalSum += mat[i, j];
    }
    }
  
    // updating first and last row separately
    for (int i = 1; i < m; i++)
    {
    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 (int j = 1; j < n; j++) 
    {
    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 (int i = 1; i < m; i++) {
    for (int j = 1; j < n; j++) {

1546
Chapter 224. Print cells with same rectangular sums in a matrix

        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
    /*
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print( sum[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print(sumr[i][j] + " ");
            }
            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)
        Console.WriteLine("(" + i + ", " + j + ")");
    }
    }
}
  
// Driver code
public static void Main()
{
    int [,]mat = {{1, 2, 3, 5},

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

Print concentric rectangular


pattern in a 2d matrix

Print concentric rectangular pattern in a 2d matrix - GeeksforGeeks


Given a positive integer n, print the matrix filled with rectangle pattern as shown below:
aaaaa
abbba
abcba
abbba
aaaaa

where a = n, b = n – 1,c = n – 2 and so on.


Examples:

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++

// C++ program for printing


// the rectangular pattern
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the pattern
void printPattern(int n)
{
    // number of rows and columns to be printed
    int s = 2 * n - 1;
  
    // Upper Half
    for (int i = 0; i < (s / 2) + 1; i++) {
         
        int m = n;
  
        // Decreasing part
        for (int j = 0; j < i; j++) {
            cout << m << " ";
            m--;
        }
  
        // Conatsant Part
        for (int k = 0; k < s - 2 * i; k++) {
            cout << n - i << " ";
        }
  
        // Increasing part.
        m = n - i + 1;
        for (int l = 0; l < i; l++) {
            cout << m << " ";
            m++;
        }

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

// Java program for printing


// the rectangular pattern
import java.io.*;
  
class GFG 
{
  
// Function to 
// print the pattern

1551
Chapter 225. Print concentric rectangular pattern in a 2d matrix

static void printPattern(int n)


{
    // number of rows and 
    // columns to be printed
    int s = 2 * n - 1;
  
    // Upper Half
    for (int i = 0;
             i < (s / 2) + 1; i++) 
    {
        int m = n;
  
        // Decreasing part
        for (int j = 0; j < i; j++) 
        {
            System.out.print(m + " ");
            m--;
        }
  
        // Constant Part
        for (int k = 0; 
                 k < s - 2 * i; k++) 
        {
            System.out.print(n - i + " ");
        }
  
        // Increasing part.
        m = n - i + 1;
        for (int l = 0; l < i; l++) 
        {
            System.out.print(m + " ");
            m++;
        }
  
        System.out.println();
    }
  
    // Lower Half
    for (int i = s / 2 - 1;
             i >= 0; i--) 
    {
  
        // Decreasing Part
        int m = n;
        for (int j = 0; j < i; j++)
        {
            System.out.print(m + " ");
            m--;

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#

// C# program for printing


// the rectangular pattern
using System;
  
class GFG 
{
  
// Function to 
// print the pattern
static void printPattern(int n)
{
    // number of rows and 
    // columns to be printed
    int s = 2 * n - 1;
  

1553
Chapter 225. Print concentric rectangular pattern in a 2d matrix

    // Upper Half


    for (int i = 0;
             i < (s / 2) + 1; i++) 
    {
        int m = n;
  
        // Decreasing part
        for (int j = 0; j < i; j++) 
        {
            Console.Write(m + " ");
            m--;
        }
  
        // Constant Part
        for (int k = 0; 
                 k < s - 2 * i; k++) 
        {
            Console.Write(n - i + " ");
        }
  
        // Increasing part.
        m = n - i + 1;
        for (int l = 0; l < i; l++) 
        {
            Console.Write(m + " ");
            m++;
        }
  
        Console.WriteLine();
    }
  
    // Lower Half
    for (int i = s / 2 - 1;
             i >= 0; i--) 
    {
  
        // Decreasing Part
        int m = n;
        for (int j = 0; j < i; j++)
        {
            Console.Write(m + " ");
            m--;
        }
  
        // Constant Part.
        for (int k = 0; 
                 k < s - 2 * i; k++)
        {

1554
Chapter 225. Print concentric rectangular pattern in a 2d matrix

            Console.Write(n - i + " ");


        }
  
        // Decreasing Part
        m = n - i + 1;
        for (int l = 0; l < i; l++) 
        {
            Console.Write(m + " ");
            m++;
        }
        Console.WriteLine();
    }
}
// Driver Code
public static void Main () 
{
    int n = 3;
  
    printPattern(n);
}
}
  
// This code is contributed 
// by anuj_67.

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

Print matrix in antispiral form

Print matrix in antispiral form - GeeksforGeeks


Given a 2D array, the task is to print matrix in anti spiral form:
Examples:

Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Input : arr[][4] = {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 :arr[][6] = {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

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++

// C++ program to print matrix in anti-spiral form


#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 5
  
void antiSpiralTraversal(int m, int n, int a[R][C])
{
    int i, k = 0, l = 0;
  
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index
        i - iterator  */
    stack<int> stk;
  
    while (k <= m && l <= n)
    {
        /* Print the first row from the remaining rows */
        for (i = l; i <= n; ++i)
            stk.push(a[k][i]);
        k++;
  
        /* Print the last column from the remaining columns */
        for (i = k; i <= m; ++i)
            stk.push(a[i][n]);
        n--;
  
        /* Print the last row from the remaining rows */
        if ( k <= m)
        {
            for (i = n; i >= l; --i)
                stk.push(a[m][i]);
            m--;
        }
  
        /* Print the first column from the remaining columns */
        if (l <= n)
        {
            for (i = m; i >= k; --i)
                stk.push(a[i][l]);
            l++;
        }

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

// JAVA Code for Print matrix in antispiral form


import java.util.*;
  
class GFG {
      
    public static void antiSpiralTraversal(int m, int n, 
                                             int a[][])
    {
        int i, k = 0, l = 0;
       
        /*  k - starting row index
            m - ending row index
            l - starting column index
            n - ending column index
            i - iterator  */
        Stack<Integer> stk=new Stack<Integer>();
       
        while (k <= m && l <= n)
        {
            /* Print the first row from the remaining 
             rows */

1558
Chapter 226. Print matrix in antispiral form

            for (i = l; i <= n; ++i)


                stk.push(a[k][i]);
            k++;
       
            /* Print the last column from the remaining
            columns */
            for (i = k; i <= m; ++i)
                stk.push(a[i][n]);
            n--;
       
            /* Print the last row from the remaining 
            rows */
            if ( k <= m)
            {
                for (i = n; i >= l; --i)
                    stk.push(a[m][i]);
                m--;
            }
       
            /* Print the first column from the remaining 
            columns */
            if (l <= n)
            {
                for (i = m; i >= k; --i)
                    stk.push(a[i][l]);
                l++;
            }
        }
       
        while (!stk.empty())
        {
            System.out.print(stk.peek() + " ");
            stk.pop();
        }
    }
      
    /* 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, 17, 18, 19, 20}
                };
               
        antiSpiralTraversal(mat.length - 1, mat[0].length - 1, 

1559
Chapter 226. Print matrix in antispiral form

                                                       mat);
    }
  }
// This code is contributed by Arnav Kr. Mandal.

Python 3

# Python 3 program to print


# matrix in anti-spiral form
R = 4
C = 5
  
def antiSpiralTraversal(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 
    stk = []
  
    while (k <= m and l <= n):
          
        # Print the first row 
        # from the remaining rows 
        for i in range(l, n + 1):
            stk.append(a[k][i])
        k += 1
  
        # Print the last column 
        # from the remaining columns 
        for i in range(k, m + 1):
            stk.append(a[i][n])
        n -= 1
  
        # Print the last row
        # from the remaining rows 
        if ( k <= m):
            for i in range(n, l - 1, -1):
                stk.append(a[m][i])
            m -= 1
  
        # Print the first column 
        # from the remaining columns 
        if (l <= n):
            for i in range(m, k - 1, -1):

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

• Diagonal traversal of Matrix


• Print matrix in spiral form
• Print a given matrix in zigzag form

Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/print-matrix-antispiral-form/

1561
Chapter 227

Print matrix in diagonal pattern

Print matrix in diagonal pattern - GeeksforGeeks


Given a matrix of n*n size, the task is to print its elements in diagonally pattern.

Input : mat[3][3] = {{1, 2, 3},


{4, 5, 6},
{7, 8, 9}}
Output : 1 2 4 7 5 3 6 8 9.

1562
Chapter 227. Print matrix in diagonal pattern

Explanation: We start from 1


Then from upward to downward diagonally i.e. 2 and 4
Then from downward to upward diagonally i.e 7,5,3
Then from up to down diagonally i.e 6, 8
Then down to up i.e. end at 9.

Input : mat[4][4] = {{1, 2, 3, 10},


{4, 5, 6, 11},
{7, 8, 9, 12},
{13, 14, 15, 16}}
Output: 1 2 4 7 5 3 10 6 8 13 14 9 11 12 15 16 .

1. We use a flag isUp to decide whether we need to go upward direction or downward


direction. We set isUp = true initially that first we are going upward.

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.

5. Do this till all the elements get traversed.

Below is the implementation of above steps.

C++

// C++ program to print matrix in diagonal order


#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
  
void printMatrixDiagonal(int mat[MAX][MAX], int n)
{
    // Initialize indexes of element to be printed next
    int i = 0, j = 0 ;
  
    // Direction is initially from down to up
    bool isUp = true;
  
    // Traverse the matrix till all elements get traversed
    for (int k=0; k<n*n;)
    {
        // If isUp = true then traverse from downward
        // to upward
        if (isUp)
        {

1563
Chapter 227. Print matrix in diagonal pattern

            for ( ; i>=0 && j<n ; j++, i--)


            {
                cout << mat[i][j] << " ";
                k++;
            }
  
            // Set i and j according 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--)
            {
                cout << 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;
    }
}
  
int main()
{
    int mat[MAX][MAX] = {{1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
  
    int n = 3;
    printMatrixDiagonal(mat, n);
    return 0;
}

Java

1564
Chapter 227. Print matrix in diagonal pattern

// Java program to print matrix in diagonal order


class GFG 
{
static final int MAX = 100;
   
static void printMatrixDiagonal(int mat[][], int n)
{
    // Initialize indexes of element to be printed next
    int i = 0, j = 0 ;
   
    // Direction is initially from down to up
    boolean isUp = true;
   
    // Traverse the matrix till all elements get traversed
    for (int k=0; k<n*n;)
    {
        // If isUp = true then traverse from downward
        // to upward
        if (isUp)
        {
            for ( ; i>=0 && j<n ; j++, i--)
            {
                System.out.print(mat[i][j] + " ");
                k++;
            }
   
            // Set i and j according 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--)
            {
                System.out.print(mat[i][j] + " ");
                k++;
            }
   
            // Set i and j according to direction
            if (j < 0 && i<=n-1)
                j = 0;
            if (i == n)

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

# Pthon 3 program to print matrix in diagonal order


MAX = 100
  
def printMatrixDiagonal(mat, n):
    # Initialize indexes of element to be printed next
    i = 0
    j = 0
    k = 0
    # Direction is initially from down to up
    isUp = True
  
     # Traverse the matrix till all elements get traversed
    while k<n*n:
         # If isUp = True then traverse from downward
         # to upward
        if isUp:
            while i >= 0 and j<n :
                print(str(mat[i][j]),end= " ")
                k +=1
                j +=1
                i -=1
  
              # Set i and j according to direction

1566
Chapter 227. Print matrix in diagonal pattern

            if i < 0 and j <= n - 1:


                i = 0
            if j == n:
                i = i+2
                j -= 1
  
         # If isUp = 0 then traverse up to down
        else:
            while j >= 0 and i<n :
                print(mat[i][j],end= " ")
                k += 1
                i += 1
                j -= 1
  
              # Set i and j according to direction
            if j < 0 and i <= n - 1:
                j = 0
            if i == n:
                j = j + 2
                i -= 1
  
         # Revert the isUp to change the direction
        isUp = not isUp
  
# Driver program
if __name__ == "__main__":
    mat = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9] ]
  
   n = 3
   printMatrixDiagonal(mat, n)
  
# This code is contributed by Chitra Nayal

C#

// Java program to print matrix in diagonal order


using System;
class GFG 
{
static int MAX = 100;
  
static void printMatrixDiagonal(int [,]mat, int n)
{
    // Initialize indexes of element to be printed next
    int i = 0, j = 0 ;
  

1567
Chapter 227. Print matrix in diagonal pattern

    // Direction is initially from down to up


    bool isUp = true;
  
    // Traverse the matrix till all elements get traversed
    for (int k=0; k<n*n;)
    {
        // If isUp = true then traverse from downward
        // to upward
        if (isUp)
        {
            for ( ; i>=0 && j<n ; j++, i--)
            {
                Console.Write(mat[i,j] + " ");
                k++;
            }
  
            // Set i and j according 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--)
            {
                Console.Write(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;
    }

  

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

Improved By : Mithun Kumar, ChitraNayal

Source

https://www.geeksforgeeks.org/print-matrix-diagonal-pattern/

1571
Chapter 228

Print matrix in snake pattern

Print matrix in snake pattern - GeeksforGeeks


Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in
the snake pattern.
Examples :

Input :mat[][] = { {10, 20, 30, 40},


{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};

Output : 10 20 30 40 45 35 25 15 27 29
37 48 50 39 33 32

Input :mat[][] = { {1, 2, 3},


{4, 5, 6},
{7, 8, 9}};
Output : 1 2 3 6 5 4 7 8 9

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++

// C++ program to print matrix in snake order


#include <iostream>
#define M 4
#define N 4
using namespace std;
  
void print(int mat[M][N])
{
    // Traverse through all rows
    for (int i = 0; i < M; i++) {
  
        // If current row is even, print from
        // left to right

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

// Java program to print matrix in snake order


import java.util.*;
class GFG
{
    static void print(int [][] mat)
    {
        // Traverse through all rows
        for (int i = 0; i < mat.length; i++)
        {
  
            // If current row is even, print from
            // left to right
            if (i % 2 == 0)
            {
                for (int j = 0; j < mat[0].length; j++)
                    System.out.print(mat[i][j] +" ");
  
  
            // If current row is odd, print from
            // right to left
            }

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

# Python 3 program to print


# matrix in snake order
M = 4
N = 4
  
def printf(mat):
    global M, N
      
    # Traverse through all rows
    for i in range(M):
          
        # If current row is
        # even, print from
        # left to right
        if i % 2 == 0:
            for j in range(N):
                print(str(mat[i][j]),
                          end = " ")
  
        # If current row is 
        # odd, print from
        # right to left

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

                    Console.Write(mat[i, j] + " ");


            }
        }
    }
  
    // Driver code
    public static void Main()
    {
        int [,]mat = {{ 10, 20, 30, 40 },
                      { 15, 25, 35, 45 },
                      { 27, 29, 37, 48 },
                      { 32, 33, 39, 50 }};
  
        print(mat);
    }
}
  
// This code is contributed
// by ChitraNayal

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

Improved By : jit_t, ChitraNayal

Source

https://www.geeksforgeeks.org/print-matrix-snake-pattern/

1578
Chapter 229

Print matrix in zag-zag fashion

Print matrix in zag-zag fashion - GeeksforGeeks


Given a matrix of 2D array of n rows and m coloumns. Print this matrix in ZIG-ZAG
fashion as shown in figure.

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

Approach of C++ code


The approach is simple. Just simply iterate over every diagonal elements one at a time and
change the direction according to the previous match.
Approach of Python3 code
This approach is simple. While travelling the matrix in the usual fashion, on basis of parity
of the sum of the indices of the element, add that particular element to the list either at
the beginning or at the end if sum of i and j is either even or odd respectively. Print the
solution list as it is.
C++

/* C++ Program to print matrix in Zig-zag pattern*/


#include <iostream>
using namespace std;
#define C 3
  
// Utility function to print matrix
// in zig-zag form
void zigZagMatrix(int arr[][C], int n, int m)
{
    int row = 0, col = 0;
  
    // Boolean variable that will true if we
    // need to increment 'row' value otherwise
    // false- if increment 'col' value
    bool row_inc = 0;
  
    // Print matrix of lower half zig-zag pattern
    int mn = min(m, n);
    for (int len = 1; len <= mn; ++len) {
        for (int i = 0; i < len; ++i) {
            cout << arr[row][col] << " ";
  
            if (i + 1 == len)
                break;
            // If row_increment value is true
            // increment row and decrement col
            // else decrement row and increment
            // col
            if (row_inc)
                ++row, --col;
            else
                --row, ++col;

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

/* Java Program to print matrix in Zig-zag pattern*/


class GFG {
  static final int C = 3;
  
  // Utility function to print matrix
  // in zig-zag form
  static void zigZagMatrix(int arr[][], int n, int m) {
    int row = 0, col = 0;
  
    // Boolean variable that will true if we

1582
Chapter 229. Print matrix in zag-zag fashion

    // need to increment 'row' value otherwise


    // false- if increment 'col' value
    boolean row_inc = false;
  
    // Print matrix of lower half zig-zag pattern
    int mn = Math.min(m, n);
    for (int len = 1; len <= mn; ++len) {
      for (int i = 0; i < len; ++i) {
        System.out.print(arr[row][col] + " ");
  
        if (i + 1 == len)
          break;
        // If row_increment value is true
        // increment row and decrement col
        // else decrement row and increment
        // col
        if (row_inc) {
          ++row;
          --col;
        } else {
          --row;
          ++col;
        }
      }
  
      if (len == mn)
        break;
  
      // Update row or col valaue 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 = true;
    } else {
      if (row == n - 1)

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

# Program to print matrix in Zig-zag pattern


  
matrix =[
            [ 1, 2, 3,],
            [ 4, 5, 6 ],
            [ 7, 8, 9 ],
        ]
rows=3
columns=3
    
solution=[[] for i in range(rows+columns-1)]
  
for i in range(rows):
    for j in range(columns):
        sum=i+j
        if(sum%2 ==0):
  
            #add at beginning
            solution[sum].insert(0,matrix[i][j])
        else:
  
            #add at end of the list
            solution[sum].append(matrix[i][j])
          
              
# print the solution as it as
for i in solution:
    for j in i:
        print(j,end=" ")
          
  
       

C#

1585
Chapter 229. Print matrix in zag-zag fashion

// C# Program to print matrix


// in Zig-zag pattern
using System;
  
class GFG {
    static int C = 3;
  
    // Utility function to print
    // matrix in zig-zag form
    static void zigZagMatrix(int[, ] arr, int n, int m)
    {
        int row = 0, col = 0;
  
        // Boolean variable that will
        // true if we need to increment
        // 'row' valueotherwise false-
        // if increment 'col' value
        bool row_inc = false;
  
        // Print matrix of lower half
        // zig-zag pattern
        int mn = Math.Min(m, n);
        for (int len = 1; len <= mn; ++len) {
                for (int i = 0; i < len; ++i) {
  
                Console.Write(arr[row, col] + " ");
  
                if (i + 1 == len)
                    break;
  
                // If row_increment value is true
                // increment row and decrement col
                // else decrement row and increment
                // col
                if (row_inc) {
                    ++row;
                    --col;
                }
                else {
                    --row;
                    ++col;
                }
            }
  
            if (len == mn)
                break;
  
            // Update row or col valaue

1586
Chapter 229. Print matrix in zag-zag fashion

            // 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 = true;
        }
        else {
            if (row == n - 1)
                ++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) {
                    Console.Write(arr[row, col] + " ");
  
                if (i + 1 == len)
                    break;
  
                // Update row or col vlaue
                // according to the last
                // increment

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

// matrix in Zig-zag pattern


$C = 3;
  
// Utility function 
// to print matrix
// in zig-zag form
function zigZagMatrix($arr,
                      $n, $m)
{
    $row = 0; $col = 0;
  
    // Boolean variable that
    // will true if we need 
    // to increment 'row' 
    // value otherwise false-
    // if increment 'col' value
    $row_inc = false;
  
    // Print matrix of lower
    // half zig-zag pattern
    $mn = min($m, $n);
    for ($len = 1; 
         $len <= $mn; $len++) 
    {
        for ($i = 0; 
             $i < $len; $i++) 
        {
            echo ($arr[$row][$col]." ");
  
            if ($i + 1 == $len)
                break;
                  
            // If row_increment value 
            // is true increment row 
            // and decrement col else 
            // decrement row and 
            // increment col
            if ($row_inc)
            {
                $row++; $col--;
            }
            else
            {
                $row--; $col++;
            }
        }
  
        if ($len == $mn)

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

            echo($arr[$row][$col] . " ");


  
            if ($i + 1 == $len)
                break;
  
            // Update row or col 
            // value 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;
  
            $row_inc = false;
        }
    }
}
  
// Driver code
$matrix = array(array(1, 2, 3),
                array(4, 5, 6),
                array(7, 8, 9));

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

Time complexity: O(n*m)


Auxiliary space: O(1)
Improved By : manishshaw1

Source

https://www.geeksforgeeks.org/print-matrix-zag-zag-fashion/

1592
Chapter 230

Print maximum sum square


sub-matrix of given size

Print maximum sum square sub-matrix of given size - GeeksforGeeks


Given an N x N matrix, find a k x k submatrix where k <= N and k >= 1, such that sum
of all the elements in submatrix is maximum. The input matrix can contain zero, positive
and negative numbers.
For example consider below matrix, if k = 3, then output should print the sub-matrix
enclosed in blue.

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.

// An efficient C++ program to find maximum sum


// sub-square matrix
#include <bits/stdc++.h>
using namespace std;
  
// Size of given matrix
#define N 5
  
// A O(n^2) function to the maximum sum sub-
// squares of size k x k in a given square
// matrix of size n x n
void printMaxSumSub(int mat[][N], 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[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;
        }
    }
  
    // max_sum stores maximum sum and its
    // position in matrix
    int max_sum = INT_MIN, *pos = NULL;

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:

Maximum sum 3 x 3 matrix is


8 6 7
4 4 4
5 5 5

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

Print n x n spiral matrix using


O(1) extra space

Print n x n spiral matrix using O(1) extra space - GeeksforGeeks


Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise
direction using O(1) space.
Example :

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

For upper right half,


mat[i][j] = (n-2*x)*(n-2*x)-(i-x)-(j-x)

For lower left half,


mat[i][j] = (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)

Below is the implementation of the idea.

C++

// C++ program to print a n x n spiral matrix


// in clockwise direction using O(1) space
#include <bits/stdc++.h>
using namespace std;
  
// Prints spiral matrix of size n x n containing
// numbers from 1 to n x n
void printSpiral(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {

1598
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 = min(min(i, j), min(n-1-i, n-1-j));
  
            // For upper right half
            if (i <= j)
                printf("%d\t ", (n-2*x)*(n-2*x) - (i-x)
                    - (j-x));
  
            // for lower left half
            else
                printf("%d\t ", (n-2*x-2)*(n-2*x-2) + (i-x)
                    + (j-x));
        }
        printf("\n");
    }
}
  
// Driver code
int main()
{
    int n = 5;
  
    // print a n x n spiral matrix in O(1) space
    printSpiral(n);
  
    return 0;
}

Java

// Java program to print a n x n spiral matrix


// in clockwise direction using O(1) space
  
import java.io.*;
import java.util.*;
  
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++) {

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

# Python3 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
def printSpiral(n) :
      
    for i in range(0, n) :
        for j in range(0, n) :
              
            # Finds minimum of four inputs

1600
Chapter 231. Print n x n spiral matrix using O(1) extra space

            x = min(min(i, j), min(n - 1 - i, n - 1 - j))


              
            # For upper right half
            if (i <= j) :
                print((n - 2 * x) * (n - 2 * x) -
                      (i - x)- (j - x), end = "\t")
  
            # For lower left half
            else :
                print(((n - 2 * x - 2) *
                       (n - 2 * x - 2) +
                       (i - x) + (j - x)), end = "\t")
        print()
          
# Driver code
n = 5
  
# print a n x n spiral matrix
# in O(1) space
printSpiral(n)
  
# This code is contributed by Nikita Tiwari.

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

            // which (i, j)th element lies


            $x;
  
            // Finds minimum of four inputs
            $x = min(min($i, $j), min($n - 1 - $i, 
                                      $n - 1 - $j));
  
            // For upper right half
            if ($i <= $j)
                echo "\t ", ($n - 2 * $x) * 
                            ($n - 2 * $x) - 
                            ($i - $x) - ($j - $x);
  
            // for lower left half
            else
                echo "\t ", ($n - 2 * $x - 2) * 
                            ($n - 2 * $x - 2) + 
                            ($i - $x) + ($j - $x);
        }
        echo "\n";
    }
}
  
// Driver code
$n = 5;
  
// print a n x n spiral
// matrix in O(1) space
printSpiral($n);
  
// This code is contributed by ajit
?>

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

Print shortest path to print a


string on screen

Print shortest path to print a string on screen - GeeksforGeeks


Given a screen containing alphabets from A-Z, we can go from one character to another
characters using a remote. The remote contains left, right, top and bottom keys.
Find shortest possible path to type all characters of given string using the remote. Initial
position is top left and all characters of input string should be printed in order.
Screen:

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.

If row difference is negative, we move up


If row difference is positive, we move down
If column difference is negative, we go left
If column difference is positive, we go right

Below is implementation of above idea


C++

// C++ program to print shortest possible path to


// type all characters of given string using a remote
#include <iostream>
using namespace std;
  
// Function to print shortest possible path to
// type all characters of given string using a remote
void printPath(string str)
{
    int i = 0;
    // start from charcater 'A' present at position (0, 0)
    int curX = 0, curY = 0;
    while (i < str.length())
    {
        // find cordinates of next character
        int nextX = (str[i] - 'A') / 5;
        int nextY = (str[i] - 'B' + 1) % 5;
  
        // Move Up if destination is above
        while (curX > nextX)
        {
            cout << "Move Up" << endl;

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

// Java program to print shortest possible path to


// type all characters of given string using a remote
  
class GFG 
{
    // Function to print shortest possible path to

1607
Chapter 232. Print shortest path to print a string on screen

    // type all characters of given string using a remote


    static void printPath(String str)
    {
        int i = 0;
        // start from charcater 'A' present at position (0, 0)
        int curX = 0, curY = 0;
        while (i < str.length())
        {
            // find cordinates of next character
            int nextX = (str.charAt(i) - 'A') / 5;
            int nextY = (str.charAt(i) - 'B' + 1) % 5;
   
            // Move Up if destination is above
            while (curX > nextX)
            {
                System.out.println("Move Up");
                curX--;
            }
   
            // Move Left if destination is to the left
            while (curY > nextY)
            {
                System.out.println("Move Left");
                curY--;
            }
   
            // Move down if destination is below
            while (curX < nextX)
            {
                System.out.println("Move Down");
                curX++;
            }
   
            // Move Right if destination is to the right
            while (curY < nextY)
            {
                System.out.println("Move Right");
                curY++;
            }
   
            // At this point, destination is reached
            System.out.println("Press OK");
            i++;
        }
    }
      
    // driver program
    public static void main (String[] args) 

1608
Chapter 232. Print shortest path to print a string on screen

    {
        String str = "COZY";
        printPath(str);
    }
}
  
// Contributed by Pramod Kumar

C#

// C# program to print shortest


// possible path to type all 
// characters of given string
// using a remote
using System;
  
class GFG {
      
    // Function to print shortest
    // possible path to type all 
    // characters of given string
    // using a remote
    static void printPath(String str)
    {
        int i = 0;
          
        // start from charcater 'A' 
        // present at position (0, 0)
        int curX = 0, curY = 0;
        while (i < str.Length)
        {
              
            // find cordinates of 
            // next character
            int nextX = (str[i] - 'A') / 5;
            int nextY = (str[i] - 'B' + 1) % 5;
  
            // Move Up if destination 
            // is above
            while (curX > nextX)
            {
                Console.WriteLine("Move Up");
                curX--;
            }
  
            // Move Left if destination 
            // is to the left
            while (curY > nextY)

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

Improved By : nitin mittal

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

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

Approach: The corner element’s index in a 2-D matrix are:

• left top corner: arr[0][0]


• right top corner: arr[0][m-1]
• left bottom corner: arr[n-1][0]
• right bottom corner: arr[n-1][m-1]

1612
Chapter 233. Print the corner elements and their sum in a 2-D matrix

Below is the implementation of the above approach.


C++

// C++ program to print the corner


// elements and their sum
#include <iostream>
using namespace std;
const int n = 3;
const int m = 3;
  
// function to print corner elements
// their sum
void printCornerElements(int arr[][m])
{
  
    // print the corner elements
    cout << "left top corner: " << arr[0][0];
    cout << "\nright top corner: " << arr[0][m - 1];
    cout << "\nleft bottom corner: " << arr[n - 1][0];
    cout << "\nright bottom corner: " << arr[n - 1][m - 1];
  
    // print the sum of corner elements
    cout << "\n\nCorner elements Sum = "
         << arr[0][0] + arr[0][m - 1]
                + arr[n - 1][0] + arr[n - 1][m - 1];
}
  
// Driver Code
int main()
{
  
    int arr[][3] = {
        { 1, 2, 4 },
        { 5, 6, 8 },
        { 8, 3, 1 }
    };
  
    // Function to print the corner
    // elements and their sum
    printCornerElements(arr);
}

Java

// Java program to print the 


// corner elements and their sum
  

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

# Python3 program to print the corner


# elements and their sum
  

1614
Chapter 233. Print the corner elements and their sum in a 2-D matrix

# function to print the


# corner element and their sum .
def printCornerElement(arr) :
      
    # no. of rows
    n = len(arr)
  
    # no. of columns
    m = len(arr[0])
  
    # print the corner elements
    print("left top corner :",arr[0][0])
    print("right top corner :",arr[0][m - 1])
    print("left bottom corner :",arr[n - 1][0])
    print("right bottom corner :",arr[n - 1][m - 1])
  
    # sum of corner elements
    corner_sum = (arr[0][0] + arr[0][m - 1] + 
           arr[n - 1][0] + arr[n - 1][m - 1])
           
    print("\ncorner elements Sum :",corner_sum)
      
  
# driver code
if __name__ == "__main__" :
  
    # 2d array 
    arr = [
        [1,2,4],
        [5,6,8],
        [8,3,1],
        ]
    # function calling
    printCornerElement(arr)

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

// elements their sum


static void printCornerElements(int[,] arr)
{
  
// print the corner elements
Console.WriteLine("left top corner: " + 
                            arr[0, 0]);
Console.WriteLine("right top corner: " + 
                         arr[0, m - 1]);
Console.WriteLine("left bottom corner: " + 
                           arr[n - 1, 0]);
Console.WriteLine("right bottom corner: " + 
                        arr[n - 1, m - 1]);
  
// print the sum of corner elements
Console.Write("\nCorner elements Sum = ");
Console.Write(arr[0, 0] + arr[0, m - 1] + 
              arr[n - 1, 0] + 
              arr[n - 1, m - 1]);
}
  
// Driver Code
public static void Main()
{
    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 Akanksha Rai(Abby_akku)

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:

left top corner: 1


right top corner: 4
left bottom corner: 8
right bottom corner: 1

Corner elements Sum = 14

Improved By : ANKITRAI1, ankita_saini, Abby_akku, ChitraNayal

Source
https://www.geeksforgeeks.org/print-the-corner-elements-and-their-sum-in-a-2-d-matrix/

1617
Chapter 234

Print unique rows in a given


boolean matrix

Print unique rows in a given boolean matrix - GeeksforGeeks


Given a binary matrix, print all unique rows of the given matrix.

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

This method will lead to Integer Overflow if number of columns is large.


Method 3 (Use Trie data structure)
Since the matrix is boolean, a variant of Trie data structure can be used where each node
will be having two children one for 0 and other for 1. Insert each row in the Trie. If the row
is already there, don’t print the row. If row is not there in Trie, insert it in Trie and print
it.
Below is C implementation of method 3.

//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

Time complexity: O( ROW x COL )


Auxiliary Space: O( ROW x COL )
This method has better time complexity. Also, relative order of rows is maintained while
printing.
Method 4 (Use HashSet data structure)
In this method convert the whole row into a single String and then check it is already present
in HashSet or not. If row is present then we will leave it otherwise we will print unique row
and add it to HashSet.
Thanks, Anshuman Kaushik for suggesting this method.

// Java code to print unique row in a 


// given binary matrix
import java.util.HashSet;
  
public class GFG {
  
    public static void printArray(int arr[][], 
                               int row,int col)
    {
          
        HashSet<String> set = new HashSet<String>();
          
        for(int i = 0; i < row; i++)
        {
            String s = "";
              
            for(int j = 0; j < col; j++) 
                s += String.valueOf(arr[i][j]);
              
            if(!set.contains(s)) {
                set.add(s);
                System.out.println(s);
                  
            }
        }
    }
      
    // Driver code
    public static void main(String[] args) {
          
        int arr[][] = { {0, 1, 0, 0, 1},
                        {1, 0, 1, 1, 0},
                        {0, 1, 0, 0, 1},
                        {1, 1, 1, 0, 0} };
          
        printArray(arr, 4, 5);
    }

1621
Chapter 234. Print unique rows in a given boolean matrix

Time complexity: O( ROW x COL )


Auxiliary Space: O(ROW)
Improved By : Anshuman Kaushik

Source

https://www.geeksforgeeks.org/print-unique-rows/

1622
Chapter 235

Printing all solutions in


N-Queen Problem

Printing all solutions in N-Queen Problem - GeeksforGeeks


The N Queen is the problem of placing N chess queens on an N×N chessboard so that no
two queens attack each other. For example, following is a solution for 4 Queen problem.
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no
two queens attack each other. For example, following are two solutions for 4 Queen problem.

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.

1) Start in the leftmost column


2) If all queens are placed
return true
3) Try all rows in the current column. Do following
for every tried row.
a) If the queen can be placed safely in this row
then mark this [row, column] as part of the
solution and recursively check if placing
queen here leads to a solution.
b) If placing queen in [row, column] leads to a
solution then return true.
c) If placing queen doesn't lead to a solution
then unmark this [row, column] (Backtrack)
and go to step (a) to try other rows.
3) If all rows have been tried and nothing worked,
return false to trigger backtracking.

There is only a slight modification in above algorithm that is highlighted in the code.

/* C/C++ program to solve N Queen Problem using

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

bool solveNQUtil(int board[N][N], int col)


{
    /* base case: If all queens are placed
    then return true */
    if (col == N)
    {
        printSolution(board);
        return true;
    }
  
    /* Consider this column and try placing
    this queen in all rows one by one */
    bool res = false;
    for (int i = 0; i < N; i++)
    {
        /* Check if queen can be placed on
        board[i][col] */
        if ( isSafe(board, i, col) )
        {
            /* Place this queen in board[i][col] */
            board[i][col] = 1;
  
            // Make result true if any placement
            // is possible
            res = solveNQUtil(board, col + 1) || res;
  
            /* If placing queen in board[i][col]
            doesn't lead to a solution, then
            remove queen from board[i][col] */
            board[i][col] = 0; // BACKTRACK
        }
    }
  
    /* If queen can not be place in any row in
        this column col then return false */
    return res;
}
  
/* This function solves the N Queen problem using
Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens
cannot be placed, otherwise return true and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
void solveNQ()
{

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

Printing brackets in Matrix


Chain Multiplication Problem

Printing brackets in Matrix Chain Multiplication Problem - GeeksforGeeks


Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)
Given a sequence of matrices, find the most efficient way to multiply these matrices together.
The problem is not actually to perform the multiplications, but merely to decide in which
order to perform the multiplications.
We have many options to multiply a chain of matrices because matrix multiplication is
associative. In other words, no matter how we parenthesize the product, the result will be
the same. For example, if we had four matrices A, B, C, and D, we would have:

(ABC)D = (AB)(CD) = A(BCD) = ....

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,

(AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations


A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.

Clearly the first parenthesization requires less number of operations.


Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of
dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return
the minimum number of multiplications needed to multiply the chain.

Input: p[] = {40, 20, 30, 10, 30}


Output: Optimal parenthesization is ((A(BC))D)
Optimal cost of parenthesization is 26000

1628
Chapter 236. Printing brackets in Matrix Chain Multiplication Problem

There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.


Let the input 4 matrices be A, B, C and D. The minimum number of
multiplications are obtained by putting parenthesis in following way
(A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30

Input: p[] = {10, 20, 30, 40, 30}


Output: Optimal parenthesization is (((AB)C)D)
Optimal cost of parenthesization is 30000
There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30.
Let the input 4 matrices be A, B, C and D. The minimum number of
multiplications are obtained by putting parenthesis in following way
((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30

Input: p[] = {10, 20, 30}


Output: Optimal parenthesization is (AB)
Optimal cost of parenthesization is 6000
There are only two matrices of dimensions 10x20 and 20x30. So there
is only one way to multiply the matrices, cost of which is 10*20*30

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.

// Prints parenthesization in subexpression (i, j)


printParenthesis(i, j, bracket[n][n], name)
{
// If only one matrix left in current segment
if (i == j)
{
print name;
name++;
return;
}

print "(";

// Recursively put brackets around subexpression


// from i to bracket[i][j].
printParenthesis(i, bracket[i][j], bracket, name);

// Recursively put brackets around subexpression


// from bracket[i][j] + 1 to j.
printParenthesis(bracket[i][j]+1, j, bracket, name);

1629
Chapter 236. Printing brackets in Matrix Chain Multiplication Problem

print ")";
}

Below is C++ implementation of above steps.

   
// 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

        are not used */


    int m[n][n];
  
    // bracket[i][j] stores optimal break point in
    // subexpression from i to j.
    int bracket[n][n];
  
    /* 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 (int i=1; i<n; i++)
        m[i][i] = 0;
  
    // L is chain length.
    for (int L=2; L<n; L++)
    {
        for (int i=1; i<n-L+1; i++)
        {
            int j = i+L-1;
            m[i][j] = INT_MAX;
            for (int k=i; k<=j-1; k++)
            {
                // q = cost/scalar multiplications
                int q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
                if (q < m[i][j])
                {
                    m[i][j] = q;
  
                    // Each entry bracket[i,j]=k shows
                    // where to split the product arr
                    // i,i+1....j for the minimum cost.
                    bracket[i][j] = k;
                }
            }
        }
    }
  
    // The first matrix is printed as 'A', next as 'B',
    // and so on
    char name = 'A';
  
    cout << "Optimal Parenthesization is : ";
    printParenthesis(1, n-1, n, (int *)bracket, name);
    cout << "nOptimal Cost is : " << m[1][n-1];
}
  

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:

Optimal Parenthesization: ((A(BC))D)


Minimum Cost of Multiplication: 26000

Time Complexity: O(n^3)


Auxiliary Space: O(n^2)

Source

https://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/

1632
Chapter 237

Printing string in plus ‘+’


pattern in the matrix

Printing string in plus ‘+’ pattern in the matrix - GeeksforGeeks


Given a string, print it inside a matrix in such a way that a ‘plus’ is formed.
Examples:

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

// CPP program to print the 


// string in 'plus' pattern
#include <bits/stdc++.h>
#define max 100
using namespace std;
  
// Function to make a cross in the matrix
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.*/
        cout << "Not possible. Please enter "
             << "odd length string.\n";
    }
    else {
  
        // declaring a 2D array i.e a matrix
        char arr[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++) {

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

// Java program to print the


// string in 'plus' pattern
class GFG {
static final int max = 100;

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

    // the array


    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            System.out.print(arr[i][j] + " ");
        }
        System.out.print("\n");
    }
    }
}
  
// Driver code
public static void main(String[] args) {
    String str = "PICTURE";
    carveCross(str);
}
}
// This code is contributed by Anant Agarwal.

C#

// C# program to print the


// string in 'plus' pattern
using System;
class GFG {
static  int max = 100;
  
// 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.
        Console.Write("Not possible. Please enter "
                            + "odd length string.");
    } 
    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++) 

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

Program for Conway’s Game Of


Life

Program for Conway’s Game Of Life - GeeksforGeeks


Initially, there is a grid with some cells which may be alive or dead. Our task to generate
the next generation of cells based on the following rules:

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

// A simple Java program to implement Game of Life


public class GameOfLife
{
    public static void main(String[] args)
    {
        int M = 10, N = 10;
  
        // Intiliazing the grid.
        int[][] grid = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
        };
  

1641
Chapter 238. Program for Conway’s Game Of Life

        // Displaying the grid


        System.out.println("Original Generation");
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                if (grid[i][j] == 0)
                    System.out.print(".");
                else
                    System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
        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) && (aliveNeighbours < 2))
                    future[l][m] = 0;
  
                // Cell dies due to over population
                else if ((grid[l][m] == 1) && (aliveNeighbours > 3))
                    future[l][m] = 0;
  
                // A new cell is born

1642
Chapter 238. Program for Conway’s Game Of Life

                else if ((grid[l][m] == 0) && (aliveNeighbours == 3))


                    future[l][m] = 1;
  
                // Remains the same
                else
                    future[l][m] = grid[l][m];
            }
        }
  
        System.out.println("Next Generation");
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                if (future[i][j] == 0)
                    System.out.print(".");
                else
                    System.out.print("*");
            }
            System.out.println();
        }
    }
}

C#

// A simple C# program to implement


// Game of Life
using System;
  
public class GFG {
      
    public static void Main()
    {
        int M = 10, N = 10;
  
        // Intiliazing the grid.
        int[,] grid = {
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }

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

                            (aliveNeighbours < 2))


                    future[l,m] = 0;
  
                // Cell dies due to over population
                else if ((grid[l,m] == 1) && 
                             (aliveNeighbours > 3))
                    future[l,m] = 0;
  
                // A new cell is born
                else if ((grid[l,m] == 0) &&
                            (aliveNeighbours == 3))
                    future[l,m] = 1;
  
                // Remains the same
                else
                    future[l,m] = grid[l,m];
            }
        }
  
        Console.WriteLine("Next Generation");
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                if (future[i,j] == 0)
                    Console.Write(".");
                else
                    Console.Write("*");
            }
            Console.WriteLine();
        }
    }
}
  
// This code is contributed by Sam007.

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

Program for Gauss-Jordan


Elimination Method

Program for Gauss-Jordan Elimination Method - GeeksforGeeks


Prerequisite : Gaussian Elimination to Solve Linear Equations
Introduction : The Gauss-Jordan method, also known as Gauss-Jordan elimination
method is used to solve a system of linear equations and is a modified version of Gauss
Elimination Method.
It is similar and simpler than Gauss Elimination Method as we have to perform 2 different
process in Gauss Elimination Method i.e.
1) Formation of upper triangular matrix, and
2) Back substitution
But in case of Gauss-Jordan Elimination Method, we only have to form a reduced row
echelon form (diagonal matrix). Below given is the flow-chart of Gauss-Jordan Elimination
Method.
Flow Chart of Gauss-Jordan Elimination Method :

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

Result is : 2.2 1.4 1.2

Explanation : Below given is the explanation of the above example.


Input Augmented Matrix is :

Interchanging R1 and R2, we get

Performing the row operation R3

1649
Chapter 239. Program for Gauss-Jordan Elimination Method

Performing the row operations R1

Performing R1

Unique Solutions are :

// C++ Implementation for Gauss-Jordan


// Elimination Method
#include <bits/stdc++.h>

1650
Chapter 239. Program for Gauss-Jordan Elimination Method

using namespace std;


  
#define M 10
  
// Function to print the matrix
void PrintMatrix(float a[][M], int n)
{
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= n; j++) 
          cout << a[i][j] << " ";
        cout << endl;
    }
}
  
// function to reduce matrix to reduced
// row echelon form.
int PerformOperation(float a[][M], int n)
{
    int i, j, k = 0, c, flag = 0, m = 0;
    float pro = 0;
      
    // Performing elementary operations
    for (i = 0; i < n; i++)
    {
        if (a[i][i] == 0) 
        {
            c = 1;
            while (a[i + c][i] == 0 && (i + c) < n) 
                c++;            
            if ((i + c) == n) {
                flag = 1;
                break;
            }
            for (j = i, k = 0; k <= n; k++) 
                swap(a[j][k], a[j+c][k]);
        }
  
        for (j = 0; j < n; j++) {
              
            // Excluding all i == j
            if (i != j) {
                  
                // Converting Matrix to reduced row
                // echelon form(diagonal matrix)
                float pro = a[j][i] / a[i][i];
  
                for (k = 0; k <= n; k++)                 
                    a[j][k] = a[j][k] - (a[i][k]) * pro;                

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:

Final Augumented Matrix is :


1 0 0 2.2
0 2 0 2.8
0 0 -2.5 -3

Result is : 2.2 1.4 1.2

Applications :

• Solving System of Linear Equations : Gauss-Jordan Elimination Method can


be used for finding the solution of a systems of linear equations which is applied
throughout the mathematics.
• Finding Determinant : The Gaussian Elimination can be applied to a square matrix
in order to find determinant of the matrix.
• Finding Inverse of Matrix : The Gauss-Jordan Elimination method can be used
in determining the inverse of a square matrix.
• Finding Ranks and Bases : Using reduced row echelon form, the ranks as well as
bases of square matrices can be computed by Gaussian elimination method.

1653
Chapter 239. Program for Gauss-Jordan Elimination Method

Source

https://www.geeksforgeeks.org/program-for-gauss-jordan-elimination-method/

1654
Chapter 240

Program for Identity Matrix

Program for Identity Matrix - GeeksforGeeks


Introduction to Identity Matrix :
The dictionary definition of an Identity Matrix is a square matrix in which all the
elements of the principal or main diagonal are 1’s and all other elements are zeros. In the
below image, every matrix is an Identity Matrix.

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.

Program to print Identity Matrix :


The logic is simple. You need to the print 1 in those positions where row is equal to column
of a matrix and make all other positions as 0.

C/C++

// C program to print Identity Matrix


#include<stdio.h>
  
int Identity(int num)
{
    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)
                printf("%d ", 1);
            else
                printf("%d ", 0);
        } 
        printf("\n");
    }
    return 0;
}
  
// Driver Code
int main()
{
    int size = 5;
    identity(size);
    return 0;
}

Java

// Java program to print Identity Matrix


class GFG {
      
    static int identity(int num)

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

# Python code to print identity matrix


  
# Function to print identity matrix
def Identity(size):
    for row in range(0, size):
        for col in range(0, size):
  
            # Here end is used to stay in same line
            if (row == col):
                print("1 ", end=" ")
            else:
                print("0 ", end=" ")
        print()
  
# Driver Code        
size = 5
Identity(size)

1657
Chapter 240. Program for Identity Matrix

C#

// C# program to print Identity Matrix


using System;
  
class GFG {
      
    static int identity(int num)
    {
        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)
                    Console.Write( 1+" ");
                else
                    Console.Write( 0+" ");
            } 
            Console.WriteLine();
        }
        return 0;
    }
      
    // Driver Code
    public static void Main()
    {
        int size = 5;
        identity(size);
    }
}
  
/*This code is contributed by vt_m.*/

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

Program to check if a given square matrix is Identity Matrix :

C++

// CPP program to check if a given matrix is identity


#include<iostream>
using namespace std;
  
const int MAX = 100;
  
bool isIdentity(int mat[][MAX], int N)

    for (int row = 0; row < N; row++)

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

// Java program to check if a given 


// matrix is identity
class GFG {
      
    int MAX = 100;
   
    static boolean isIdentity(int mat[][], int N)
    { 
        for (int row = 0; row < N; row++)
        {
            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;

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

# Python3 program to check 


# if a given matrix is identity
MAX = 100;
def isIdentity(mat, N):
    for row in range(N):
        for col in range(N):
            if (row == col and 
                mat[row][col] != 1):
                return False;
            elif (row != col and 
                  mat[row][col] != 0):
                return False;
    return True;
  
# Driver Code
N = 4;
mat = [[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]]; 
if (isIdentity(mat, N)):
    print("Yes ");
else:
    print("No ");
  

1661
Chapter 240. Program for Identity Matrix

# This code is contributed


# by mits

C#

// C# program to check if a given 


// matrix is identity
using System;
  
class GFG {
      
    //int MAX = 100;
  
    static bool isIdentity(int[,] mat, int N)
    { 
        for (int row = 0; row < N; row++)
        {
            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
    public static void Main()
    {
        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))
        Console.WriteLine("Yes ");
        else
        Console.WriteLine("No ");
    }
}
  
  
/*This code is contributed by vt_m.*/

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

Improved By : vt_m, Mithun Kumar

Source

https://www.geeksforgeeks.org/program-print-identity-matrix/

1663
Chapter 241

Program for Markov matrix

Program for Markov matrix - GeeksforGeeks


Given a m x n 2D matrix, check if it is a Markov Matrix.
Markov Matrix : The matrix in which the sum of each row is equal to 1.

Example of Markov Matrix


Examples:

Input :
1 0 0
0.5 0 0.5
0 0 1
Output : yes

Explanation :

1664
Chapter 241. Program for Markov matrix

Sum of each row results to 1,


therefore it is a Markov Matrix.

Input :
1 0 0
0 0 2
1 0 0
Output :
no

Approach : Initialize a 2D array, then take another single dimensional array to store the
sum of each rows of the matrix, and check whether all the sum stored in this 1D array is
equal to 1, if yes then it is Markov matrix else not.

C++

// C++ code to check Markov Matrix


#include <iostream>
using namespace std;
  
#define n 3
  
bool checkMarkov(double m[][n])
{
    // outer loop to access rows
    // and inner to access columns
    for (int i = 0; i <n; i++) {
  
        // Find sum of current row
        double sum = 0;
        for (int j = 0; j < n; j++)
            sum = sum + m[i][j];
  
        if (sum != 1)
        return false;
    }
  
    return true;
}
  
// Driver Code
int main() 
{
    // Matrix to check
    double m[3][3] = { { 0, 0, 1 },
                    { 0.5, 0, 0.5 },
                    { 1, 0, 0 } };

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

// Java code to check Markov Matrix


import java.io.*;
  
public class markov
{
    static boolean checkMarkov(double m[][])
    {
        // outer loop to access rows
        // and inner to access columns
        for (int i = 0; i < m.length; i++) {
  
            // Find sum of current row
            double sum = 0;
            for (int j = 0; j < m[i].length; j++)
                sum = sum + m[i][j];
  
            if (sum != 1)
               return false;
        }
  
        return true;
    }
  
    public static void main(String args[])
    {
        // Matrix to check
        double m[][] = { { 0, 0, 1 },
                         { 0.5, 0, 0.5 },
                         { 1, 0, 0 } };
  
        // calls the function check()
        if (checkMarkov(m))
            System.out.println(" yes ");
        else
            System.out.println(" no ");
    }

1666
Chapter 241. Program for Markov matrix

Python3

# Python 3 code to check Markov Matrix


  
def checkMarkov(m) :
      
    # Outer loop to access rows
    # and inner to access columns
    for i in range(0, len(m)) :
          
        # Find sum of current row
        sm = 0
        for j in range(0, len(m[i])) :
            sm = sm + m[i][j]
  
        if (sm != 1) :
            return False
              
    return True
      
# Matrix to check
m = [ [ 0, 0, 1 ],
      [ 0.5, 0, 0.5 ],
      [ 1, 0, 0 ]      ]
  
# Calls the function check()
if (checkMarkov(m)) :
    print(" yes ")
else :
    print(" no ")
      
      
# This code is contributed by Nikita Tiwari.

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

    // rows and inner to 


    // access columns
    for (int i = 0;
             i < m.GetLength(0); i++) 
    {
  
        // Find sum of 
        // current row
        double sum = 0;
        for (int j = 0; 
                 j < m.GetLength(1); j++)
            sum = sum + m[i, j];
  
        if (sum != 1)
        return false;
    }
  
    return true;
}
  
// Driver Code
static void Main()
{
    // Matrix to check
    double [,]m = new double[,]{{ 0, 0, 1},
                                {0.5, 0, 0.5},
                                {1, 0, 0}};
  
    // calls the 
    // function check()
    if (checkMarkov(m))
        Console.WriteLine(" yes ");
    else
        Console.WriteLine(" no ");
}
}
  
// This code is contributed by 
// Manish Shaw(manishshaw1)

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

Improved By : nitin mittal, manishshaw1

Source

https://www.geeksforgeeks.org/markov-matrix/

1669
Chapter 242

Program for Rank of Matrix

Program for Rank of Matrix - GeeksforGeeks


What is rank of a matrix?
Rank of a matrix A of size M x N is defined as
(a) Maximum number of linearly independent column vectors in the matrix or
(b) Maximum number of linearly independent row vectors in the matrix.

Example:

Input: mat[][] = {{10, 20, 10},


{20, 40, 20},
{30, 50, 0}}
Output: Rank is 2
Explanation: Ist and IInd rows are linearly dependent.
But Ist and 3rd or IInd and IIIrd are
independent.

Input: mat[][] = {{10, 20, 10},


{-20, -30, 10},
{30, 50, 0}}
Output: Rank is 2
Explanation: Ist and IInd rows are linearly independent.
So rank must be atleast 2. But all three rows
are linearly dependent (the first is equal to
the sum of the second and third) so the rank
must be less than 3.

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.

1) Let the input matrix be mat[][]. Initialize rank equals


to number of columns

// Before we visit row 'row', traversal of previous


// rows make sure that mat[row][0],....mat[row][row-1]
// are 0.
2) Do following for row = 0 to rank-1.

a) If mat[row][row] is not zero, make all elements of


current column as 0 except the element mat[row][row]
by finding appropriate multiplier and adding a the
multiple of row 'row'

b) Else (mat[row][row] is zero). Two cases arise:


(i) If there is a row below it with non-zero entry in
same column, then swap current 'row' and that row.
(ii) If all elements in current column below mat[r][row]
are 0, then remove this column by swapping it with
last column and reducing number of rank by 1.
Reduce row by 1 so that this row is processed again.

3) Number of remaining columns is rank of matrix.

Example:

Input: mat[][] = {{10, 20, 10},


{-20, -30, 10},
{30, 50, 0}}

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

mat[][] = {{10, 20, 10},


{ 0, 10, 30},
{ 0, -10, -30}}

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.

Below is the implementation of above idea.


C++

// C++ program to find rank of a matrix


#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
  
/* function for exchanging two rows of
   a matrix */
void swap(int mat[R][C], int row1, int row2,
          int col)
{
    for (int i = 0; i < col; i++)
    {
        int temp = mat[row1][i];
        mat[row1][i] = mat[row2][i];
        mat[row2][i] = temp;
    }
}
  
// Function to display a matrix

1672
Chapter 242. Program for Rank of Matrix

void display(int mat[R][C], int row, int col);


  
/* function for finding rank of matrix */
int rankOfMatrix(int mat[R][C])
{
    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])
        {
           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
        {
            bool reduce = true;
  
            /* Find the non-zero element in current
                column  */
            for (int i = row + 1; i < R;  i++)
            {
                // Swap the row with non-zero element

1673
Chapter 242. Program for Rank of Matrix

                // with this row.


                if (mat[i][row])
                {
                    swap(mat, row, i, rank);
                    reduce = false;
                    break ;
                }
            }
  
            // If we did not find any row with non-zero
            // element in current columnm, then all
            // values in this column are 0.
            if (reduce)
            {
                // Reduce number of columns
                rank--;
  
                // Copy the last column here
                for (int i = 0; i < R; i ++)
                    mat[i][row] = mat[i][rank];
            }
  
            // Process this row again
            row--;
        }
  
       // Uncomment these lines to see intermediate results
       // display(mat, R, C);
       // printf("\n");
    }
    return rank;
}
  
/* function for displaying the matrix */
void display(int mat[R][C], 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[][3] = {{10,   20,   10},

1674
Chapter 242. Program for Rank of Matrix

                  {-20,  -30,   10},


                   {30,   50,   0}};
    printf("Rank of the matrix is : %d",
         rankOfMatrix(mat));
    return 0;
}

Java

// Java program to find rank of a matrix


class GFG {
      
    static final int R = 3;
    static final int C = 3;
      
    // function for exchanging two rows
    // of a matrix 
    static void swap(int mat[][], 
          int row1, int row2, int col)
    {
        for (int i = 0; i < col; i++)
        {
            int temp = mat[row1][i];
            mat[row1][i] = mat[row2][i];
            mat[row2][i] = temp;
        }
    }
      
    // Function to display a matrix
    static void display(int mat[][], 
                     int row, int col)
    {
        for (int i = 0; i < row; i++)
        {
              
            for (int j = 0; j < col; j++)
              
                System.out.print(" "
                          + mat[i][j]);
                            
            System.out.print("\n");
        }
    } 
      
    // function for finding rank of matrix 
    static int rankOfMatrix(int mat[][])
    {
          

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

                // Find the non-zero element 


                // in current column 
                for (int i = row + 1; i < R; i++)
                {
                    // Swap the row with non-zero 
                    // element with this row.
                    if (mat[i][row] != 0)
                    {
                        swap(mat, row, i, rank);
                        reduce = false;
                        break ;
                    }
                }
      
                // If we did not find any row with 
                // non-zero element in current 
                // columnm, then all values in 
                // this column are 0.
                if (reduce)
                {
                    // Reduce number of columns
                    rank--;
      
                    // Copy the last column here
                    for (int i = 0; i < R; i ++)
                        mat[i][row] = mat[i][rank];
                }
      
                // Process this row again
                row--;
            }
      
        // Uncomment these lines to see 
        // intermediate results display(mat, R, C);
        // printf("\n");
        }
          
        return rank;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        int mat[][] = {{10, 20, 10},
                       {-20, -30, 10},
                       {30, 50, 0}};
                         
        System.out.print("Rank of the matrix is : " 

1677
Chapter 242. Program for Rank of Matrix

                               + rankOfMatrix(mat));
    }
}
  
// This code is contributed by Anant Agarwal.

C#

// C# program to find rank of a matrix


using System;
class GFG {
       
    static  int R = 3;
    static  int C = 3;
       
    // function for exchanging two rows
    // of a matrix 
    static void swap(int [,]mat, 
          int row1, int row2, int col)
    {
        for (int i = 0; i < col; i++)
        {
            int temp = mat[row1,i];
            mat[row1,i] = mat[row2,i];
            mat[row2,i] = temp;
        }
    }
       
    // Function to display a 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");
        }
    } 
       
    // function for finding rank of matrix 
    static int rankOfMatrix(int [,]mat)
    {
           

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

                // Find the non-zero element 


                // in current column 
                for (int i = row + 1; i < R; i++)
                {
                    // Swap the row with non-zero 
                    // element with this row.
                    if (mat[i,row] != 0)
                    {
                        swap(mat, row, i, rank);
                        reduce = false;
                        break ;
                    }
                }
       
                // If we did not find any row with 
                // non-zero element in current 
                // columnm, then all values in 
                // this column are 0.
                if (reduce)
                {
                    // Reduce number of columns
                    rank--;
       
                    // Copy the last column here
                    for (int i = 0; i < R; i ++)
                        mat[i,row] = mat[i,rank];
                }
       
                // Process this row again
                row--;
            }
       
        // Uncomment these lines to see 
        // intermediate results display(mat, R, C);
        // printf("\n");
        }
           
        return rank;
    }
       
    // Driver code
    public static void Main ()
    {
        int [,]mat = {{10, 20, 10},
                       {-20, -30, 10},
                       {30, 50, 0}};
                          
        Console.Write("Rank of the matrix is : "

1680
Chapter 242. Program for Rank of Matrix

                          + rankOfMatrix(mat));
    }
}
   
// This code is contributed by nitin mittal

Output:

Rank of the matrix is : 2

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

Program for Sudoku Generator

Program for Sudoku Generator - GeeksforGeeks


Background:
Following are the rules of Suduku for a player.

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.

1. Randomly take any number 1-9.


2. Check if it is safe to put in the cell.(row , column and box)
3. If safe, place it and increment to next location and go to step 1.
4. If not safe, then without incrementing go to step 1.
5. Once matrix is fully filled, remove k no. of elements randomly to complete game.

Improved Solution : We can improve the solution, if we understand a pattern in this


game. We can observe that all 3 x 3 matrices, which are diagonally present are independent
of other 3 x 3 adjacent matrices initially, as others are empty.

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.

Following is the improved logic for the problem.


1. Fill all the diagonal 3x3 matrices.
2. Fill recursively rest of the non-diagonal matrices.
For every cell to be filled, we try all numbers until
we find a safe number to be placed.
3. Once matrix is fully filled, remove K elements
randomly to complete game.

/* Java program for Sudoku generator  */


import java.lang.*;
  
public class Sudoku
{
    int[] mat[];
    int N; // number of columns/rows.
    int SRN; // square root of N
    int K; // No. Of missing digits
  
    // Constructor
    Sudoku(int N, int K)
    {
        this.N = N;
        this.K = K;
  
        // Compute square root of N
        Double SRNd = Math.sqrt(N);
        SRN = SRNd.intValue();
  
        mat = new int[N][N];
    }
  
    // Sudoku Generator
    public void fillValues()
    {
        // Fill the diagonal of SRN x SRN matrices
        fillDiagonal();

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

    // Random generator


    int randomGenerator(int num)
    {
        return (int) Math.floor((Math.random()*num+1));
    }
  
    // Check if safe to put in cell
    boolean CheckIfSafe(int i,int j,int num)
    {
        return (unUsedInRow(i, num) &&
                unUsedInCol(j, num) &&
                unUsedInBox(i-i%SRN, j-j%SRN, num));
    }
  
    // check in the row for existence
    boolean unUsedInRow(int i,int num)
    {
        for (int j = 0; j<N; j++)
           if (mat[i][j] == num)
                return false;
        return true;
    }
  
    // check in the row for existence
    boolean unUsedInCol(int j,int num)
    {
        for (int i = 0; i<N; i++)
            if (mat[i][j] == num)
                return false;
        return true;
    }
  
    // A recursive function to fill remaining 
    // matrix
    boolean fillRemaining(int i, int j)
    {
        //  System.out.println(i+" "+j);
        if (j>=N && i<N-1)
        {
            i = i + 1;
            j = 0;
        }
        if (i>=N && j>=N)
            return true;
  
        if (i < SRN)
        {
            if (j < SRN)

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

            // System.out.println(i+" "+j);


            if (mat[i][j] != 0)
            {
                count--;
                mat[i][j] = 0;
            }
        }
    }
  
    // Print sudoku
    public void printSudoku()
    {
        for (int i = 0; i<N; i++)
        {
            for (int j = 0; j<N; j++)
                System.out.print(mat[i][j] + " ");
            System.out.println();
        }
        System.out.println();
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int N = 9, K = 20;
        Sudoku sudoku = new Sudoku(N, K);
        sudoku.fillValues();
        sudoku.printSudoku();
    }
}

Output: [0 means not filled]

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

Program for scalar


multiplication of a matrix

Program for scalar multiplication of a matrix - GeeksforGeeks


Given a matrix and a scalar element k, our task is to find out the scalar product of that
matrix.
Examples:

Input : mat[][] = {{2, 3}


{5, 4}}
k = 5
Output : 10 15
25 20
We multiply 5 with every element.

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++

// C++ program to find the scalar product 


// of a matrix

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

// Java program to find


// the scalar product 
// of a matrix
import java.io.*;
  
class GFG {
      
static final int N = 3;
static void scalarProductMat(int mat[][], 
                                  int k)
{

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

    for (int i = 0; i < N; i++) 


        for (int j = 0; j < N; j++) 
            mat[i,j] = mat[i, j] * k;     
}
  
// Driver code
static public void Main ()
{
    int[,] mat = {{1, 2, 3},
                  {4, 5, 6},
                  {7, 8, 9}};
    int k = 4;
  
    scalarProductMat(mat, k);
  
    // to display the resultant matrix
    Console.WriteLine("Scalar Product Matrix is : ");
      
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) 
            Console.Write(mat[i, j] + " ");
        Console.WriteLine();
    }
}
}
  
// This code is contributed by Ajit.

Output:

Scalar Product Matrix is :


4 8 12
16 20 24
28 32 36

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

Program to Interchange Diagonals of Matrix - GeeksforGeeks


Given a square matrix of order n*n, you have to interchange the elements of both diagonals.

Examples :

Input : matrix[][] = {1, 2, 3,


4, 5, 6,
7, 8, 9}
Output : matrix[][] = {3, 2, 1,
4, 5, 6,
9, 8, 7}

Input : matrix[][] = {4, 2, 3, 1,


5, 7, 6, 8,
9, 11, 10, 12,
16, 14, 15, 13}
Output : matrix[][] = {1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
11, 14, 15, 16}

Expalnation : Idea behind interchanging diagonals of square matrix is simple. Iterate


from 0 to n-1 and for each iteration you have to swap a[i][i] and a[i][n-i-1].

1692
Chapter 245. Program to Interchange Diagonals of Matrix

Time complexity : O(n)

// 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

    for (int i = 0; i < N; ++i)


    {
    for (int j = 0; j < N; ++j)
            printf(" %d", array[i][j]);
    printf("\n");
    }
}
  
// Driver Code
int main()
{
    int array[N][N] = {4, 5, 6,
                    1, 2, 3,
                    7, 8, 9};
    interchangeDiagonals(array);
    return 0;
}

Java

// Java program to interchange 


// the diagonals of matrix
import java.io.*;
  
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)
                System.out.print(array[i][j]+" ");
            System.out.println();
        }
    }
      

1694
Chapter 245. Program to Interchange Diagonals of Matrix

    // Driver Code


    public static void main (String[] args) 
    {
        int array[][] = { {4, 5, 6},
                        {1, 2, 3},
                        {7, 8, 9}
                        };
        interchangeDiagonals(array);
    }
}
  
// This code is contributed by Pramod Kumar

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

Program to Print Matrix in Z


form

Program to Print Matrix in Z form - GeeksforGeeks


Given a square matrix of order n*n, we need to print elements of the matrix in Z form

Examples:
Input : mat[][] = {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output : 1 2 3 5 7 8 9

Input : mat[][] = {5, 19, 8, 7,


4, 1, 14, 8,
2, 20, 1, 9,
1, 2, 55, 4}
Output: 5 19 8 7 14 20 1 2 55 4

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

// CPP program to print a square matrix in Z form


#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
  
// Function to print a square matrix in Z form
void printZform(int mat[][MAX], int n)
{
    // print first row
    for (int i = 0; i < n; i++)
        cout << mat[0][i] << " ";
  
    // Print diagonal
    int i = 1, j = n - 2;
    while (i < n && j >= 0) // print diagonal
    {
        cout << mat[i][j] << " ";
        i++;
        j--;
    }

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

// Java program to print a


// square matrix in Z form
  
import java.lang.*;
import java.io.*;
  
class GFG {
    public static void diag(int arr[][], int n)
    {
        int i = 0, j, k;
  
        // print first row
        for (j = 0; j < n - 1; j++) {
            System.out.print(arr[i][j] + " ");
        }
  
        // Print diagonal
        k = 1;
        for (i = 0; i < n - 1; i++) {
            for (j = 0; j < n; j++) {
                if (j == n - k) {
                    System.out.print(arr[i][j] + " ");
                    break;
                }
            }
            k++;
        }
        // Print last row
        i = n - 1;

1699
Chapter 246. Program to Print Matrix in Z form

        for (j = 0; j < n; j++)


            System.out.print(arr[i][j] + " ");
  
        System.out.print("\n");
    }
  
    public static void main(String[] args)
    {
        int a[][] = { { 4, 5, 6, 8 },
                      { 1, 2, 3, 1 },
                      { 7, 8, 9, 4 },
                      { 1, 8, 7, 5 } };
  
        diag(a, 4);
    }
}
  
// Code contributed by Mohit Gupta_OMG <(0_o)>

Python3

# Python program to print a 


# square matrix in Z form
  
arr = [[4, 5, 6, 8], 
        [1, 2, 3, 1], 
        [7, 8, 9, 4], 
        [1, 8, 7, 5]]
  
n = len(arr[0])
                   
i = 0
for j in range(0, n-1):
    print(arr[i][j], end = ' ') 
          
k = 1
for i in range(0, n):
    for j in range(n, 0, -1):
        if(j == n-k):
            print(arr[i][j], end = ' ') 
            break; 
    k+= 1
  
# Print last row
i = n-1; 
for j in range(0, n):
    print(arr[i][j], end = ' ')
  

1700
Chapter 246. Program to Print Matrix in Z form

# Code contributed by Mohit Gupta_OMG <(0_o)>

C#

// C# program to print a square 


// matrix in Z form
using System;
  
class GFG {
      
    public static void printZform(int[, ] mat, int n)
    {
  
        int i, j;
          
        // print first row
        for (i = 0; i < n; i++) {
            Console.Write(mat[0, i] + " ");
        }
  
        // Print diagonal
        i = 1;
        j = n - 2;
      
        while (i < n && j >= 0) // print diagonal
        {
            Console.Write(mat[i,j] + " ");
            i++;
            j--;
        }
      
        // Print last row
        for (i = 1; i < n; i++)
            Console.Write(mat[n - 1,i] + " ");
    }
  
    // Driver code
    public static void Main()
    {
        int[, ] mat = { { 4, 5, 6, 8 },
                    { 1, 2, 3, 1 },
                    { 7, 8, 9, 4 },
                    { 1, 8, 7, 5 } };
  
        printZform(mat, 4);
    }
}
  

1701
Chapter 246. Program to Print Matrix in Z form

// This code is contributed by vt_m.

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

Program to check Involutory


Matrix

Program to check Involutory Matrix - GeeksforGeeks


Given a matrix and the task is to check matrix is involutory matrix or not.
Involutory Matrix: A matrix is said to be involutory matrix if matrix multiply by itself
return the identity matrix. Involutory matrix is the matrix that is its own inverse. The
matrix A is said to be involutory matrix if A * A = I. Where I is the identity matrix.

Examples:

Input : mat[N][N] = {{1, 0, 0},


{0, -1, 0},
{0, 0, -1}}
Output : Involutory Matrix

Input : mat[N][N] = {{1, 0, 0},


{0, 1, 0},
{0, 0, 1}}
Output : Involutory Matrix

C++

1704
Chapter 247. Program to check Involutory Matrix

// Program to implement involutory matrix.


#include <bits/stdc++.h>
#define N 3
using namespace std;
  
// Function for matrix multiplication.
void multiply(int mat[][N], int res[][N])
{
    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.
bool InvolutoryMatrix(int mat[N][N])
{
    int res[N][N];
  
    // multiply function call.
    multiply(mat, res);
  
    for (int i = 0; i < N; i++) {
        for (int 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 function.
int main()
{
    int mat[N][N] = { { 1, 0, 0 },
                      { 0, -1, 0 },
                      { 0, 0, -1 } };
  
    // Function call. If function return
    // true then if part will execute otherwise
    // else part will execute.
    if (InvolutoryMatrix(mat))
        cout << "Involutory Matrix";

1705
Chapter 247. Program to check Involutory Matrix

    else
        cout << "Not Involutory Matrix";
  
    return 0;
}

Java

// Java  Program to implement 


// involutory matrix.
import java.io.*;
  
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 boolean InvolutoryMatrix(int mat[][])
    {
        int res[][] = new int[N][N];
      
        // multiply function call.
        multiply(mat, res);
      
        for (int i = 0; i < N; i++) {
            for (int 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 function.

1706
Chapter 247. Program to check Involutory Matrix

    public static void main (String[] args) 


    {
          
        int mat[][] = { { 1, 0, 0 },
                        { 0, -1, 0 },
                        { 0, 0, -1 } };
      
        // Function call. If function return
        // true then if part will execute 
        // otherwise else part will execute.
        if (InvolutoryMatrix(mat))
            System.out.println ( "Involutory Matrix");
        else
            System.out.println ( "Not Involutory Matrix");
      
              
    }
}
  
// This code is contributed by vt_m

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

        // multiply function call.


        multiply(mat, res);
      
        for (int i = 0; i < N; i++) {
            for (int 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 function.
    public static void Main () 
    {
          
        int [,]mat = { { 1, 0, 0 },
                        { 0, -1, 0 },
                        { 0, 0, -1 } };
      
        // Function call. If function return
        // true then if part will execute 
        // otherwise else part will execute.
        if (InvolutoryMatrix(mat))
            Console.WriteLine( "Involutory Matrix");
        else
            Console.WriteLine( "Not Involutory Matrix");
      
              
    }
}
  
// This code is contributed by vt_m

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

// return true then if part 


// will execute otherwise
// else part will execute.
if (InvolutoryMatrix($mat))
    echo "Involutory Matrix";
else
    echo "Not Involutory Matrix";
  
// This code is contributed by mits
?>

Output :

Involutory Matrix

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/program-check-involutory-matrix/

1710
Chapter 248

Program to check diagonal


matrix and scalar matrix

Program to check diagonal matrix and scalar matrix - GeeksforGeeks


Diagonal matrix:
A square matrix is said to be diagonal matrix if the elements of matrix except main diagonal
are zero. A square null matrix is also a diagonal matrix whose main diagonal elements are
zero.
Examples :

Input :
Mat[4][0] = {{4, 0, 0, 0},
{0, 5, 0, 0},
{0, 0, 2, 0},
{0, 0, 0, 1}}
Output : Yes

Mat[4][0] = {{6, 10, 12, 0},


{0, 5, 0, 0},
{0, 0, 9, 0},
{0, 0, 0, 1}}
Output : No

CPP

// Program to check matrix is diagonal matrix or not.


#include <bits/stdc++.h>
#define N 4
using namespace std;
  

1711
Chapter 248. Program to check diagonal matrix and scalar matrix

// Function to check matrix is diagonal matrix


// or not.
bool isDiagonalMatrix(int mat[N][N])
{
    for (int i = 0; i < N; i++)
        for (int 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 function
int main()
{
    int mat[N][N] = { { 4, 0, 0, 0 },
                      { 0, 7, 0, 0 },
                      { 0, 0, 5, 0 },
                      { 0, 0, 0, 1 } };
  
    if (isDiagonalMatrix(mat))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}

Java

// Program to check matrix is


// diagonal matrix or not.
  
import java.io.*;
  
class GFG {
      
    static int N = 4;
      
    // Function to check matrix
    // is diagonal matrix
    // or not.
    static boolean isDiagonalMatrix(int mat[][])
    {
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
       

1712
Chapter 248. Program to check diagonal matrix and scalar matrix

                // condition to check


                // other elements 
                // except main diagonal 
                // are zero or not.
                if ((i != j) &&
                   (mat[i][j] != 0))
                    return false;
  
        return true;
    }
       
    // Driver function
    public static void main(String args[])
    {
        int mat[][] = { { 4, 0, 0, 0 },
                          { 0, 7, 0, 0 },
                          { 0, 0, 5, 0 },
                          { 0, 0, 0, 1 } };
       
        if (isDiagonalMatrix(mat))
            System.out.println("Yes");
        else
            System.out.println("No" );
    }
}
  
// This code is contributed by
// Nikita Tiwari.

Python3

# Python3 Program to check if matrix


# is diagonal matrix or not.
  
N = 4
  
# Function to check matrix
# is diagonal matrix
# or not.   
def isDiagonalMatrix(mat) :
    for i in range(0, N):
        for j in range(0, N) :
              
            # condition to check
            # other elements 
            # except main diagonal
            # are zero or not.
            if ((i != j) and

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#

// Program to check matrix is


// diagonal matrix or not.
using System;
  
class GFG {
      
    static int N = 4;
      
    // Function to check matrix
    // is diagonal matrix
    // or not.
    static bool isDiagonalMatrix(int [,]mat)
    {
        for (int i = 0; i < N; i++)
            for (int 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;
    }
      

1714
Chapter 248. Program to check diagonal matrix and scalar matrix

    // Driver function


    public static void Main()
    {
        int [,]mat = { { 4, 0, 0, 0 },
                        { 0, 7, 0, 0 },
                        { 0, 0, 5, 0 },
                        { 0, 0, 0, 1 } };
      
        if (isDiagonalMatrix(mat))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No" );
    }
}
  
// This code is contributed by
// vt_m.

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

Mat[4][4] = {{4, 0, 0, 0},


{0, 4, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 4}}
Output : No

CPP

// Program to check matrix is scalar matrix or not.


#include <bits/stdc++.h>
#define N 4
using namespace std;
  
// Function to check matrix is scalar matrix or not.
bool isScalarMatrix(int mat[N][N])
{
    // Check all elements except main diagonal are

1716
Chapter 248. Program to check diagonal matrix and scalar matrix

    // zero or not.


    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            if ((i != j) && (mat[i][j] != 0))
                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
int main()
{
    int mat[N][N] = { { 2, 0, 0, 0 },
                      { 0, 2, 0, 0 },
                      { 0, 0, 2, 0 },
                      { 0, 0, 0, 2 } };
    // Function call
    if (isScalarMatrix(mat))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}

Java

// Program to check matrix


// is scalar matrix or not.
import java.io.*;
  
class GFG {
      
    static int N = 4;
    // Function to check matrix
    // is scalar matrix or not.
    static boolean isScalarMatrix(int mat[][])
    {
        // Check all elements
        // except main diagonal are
        // zero or not.
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
                if ((i != j)
                  && (mat[i][j] != 0))

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

# Program to check matrix


# is scalar matrix or not.
  
  
N = 4
  
# Function to check matrix is
# scalar matrix or not.
def isScalarMatrix(mat) :
      
    # Check all elements 
    # except main diagonal are
    # zero or not.
    for i in range(0,N) :
        for j in range(0,N) :
            if ((i != j) 
               and (mat[i][j] != 0)) :
                return False

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#

// Program to check matrix


// is scalar matrix or not.
using System;
  
class GFG {
      
    static int N = 4;
      
    // Function to check matrix
    // is scalar matrix or not.
    static bool isScalarMatrix(int [,]mat)
    {
        // Check all elements
        // except main diagonal are
        // zero or not.
        for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
                if ((i != j) && (mat[i,j] != 0))
                    return false;

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

    // Check all diagonal elements 


    // are same or not.
    for ($i = 0; $i < $N - 1; $i++)
        if ($mat[$i][$i] != $mat[$i + 1][$i + 1])
            return false;
    return true;
}
  
// Driver Code
$mat = array(array(2, 0, 0, 0),
             array(0, 2, 0, 0),
             array(0, 0, 2, 0),
             array(0, 0, 0, 2));
               
// Function call
if (isScalarMatrix($mat))
    echo "Yes";
else
    echo "No" ;
  
// This code is contributed by mits
?>

Output :

Yes

Improved By : jit_t, Mithun Kumar

Source

https://www.geeksforgeeks.org/program-check-diagonal-matrix-scalar-matrix/

1721
Chapter 249

Program to check idempotent


matrix

Program to check idempotent matrix - GeeksforGeeks


Given a N * N matrix and the task is to check matrix is idempotent matrix or not.
Idempotent matrix: A matrix is said to be idempotent matrix if matrix multiplied by
itself return the same matrix. The matrix M is said to be idempotent matrix if and only if
M * M = M. In idempotent matrix M is a square matrix.

Examples:

Input : mat[][] = {{3, -6},


{1, -2}};
Output : Idempotent Matrix

Input : mat[N][N] = {{2, -2, -4},


{-1, 3, 4},
{1, -2, -3}}
Output : Idempotent Matrix.

C++

1722
Chapter 249. Program to check idempotent matrix

// Program to check given matrix 


// is idempotent matrix or not.
#include<bits/stdc++.h>
#define N 3
using namespace std;
  
// Function for matrix multiplication.
void multiply(int mat[][N], int res[][N])
{
    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 idempotent
// property of matrix.
bool checkIdempotent(int mat[][N])
{   
    // Calculate multiplication of matrix
    // with itself and store it into res.
    int res[N][N];
    multiply(mat, res);
  
    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 function.
int main()
{
    int mat[N][N] = {{2, -2, -4},
                    {-1, 3, 4},
                    {1, -2, -3}};
      
    // checkIdempotent function call.
    if (checkIdempotent(mat))
        cout << "Idempotent Matrix";
    else
        cout << "Not Idempotent Matrix.";

1723
Chapter 249. Program to check idempotent matrix

    return 0;
}

Java

// Java program to check given matrix 


// is idempotent matrix or not.
import java.io.*;
  
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 idempotent
    // property of matrix.
    static boolean checkIdempotent(int mat[][])
    { 
        // Calculate multiplication of matrix
        // with itself and store it into res.
        int res[][] = new int[N][N];
        multiply(mat, res);
      
        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.

1724
Chapter 249. Program to check idempotent matrix

    public static void main (String[] args) 


    {
        int mat[][] = {{2, -2, -4},
                       {-1, 3, 4},
                       {1, -2, -3}};
      
        // checkIdempotent function call.
        if (checkIdempotent(mat))
            System.out.println( "Idempotent Matrix");
        else
            System.out.println("Not Idempotent Matrix.");
          
    }
}
  
// This code is contributed by vt_m.

Python 3

# Python Program to check given matrix 


# is idempotent matrix or not.
import math
  
# Function for matrix multiplication.
def multiply(mat, res):
  
    N= len(mat)
    for i in range(0,N):
      
        for j in range(0,N):
          
            res[i][j] = 0
            for k in range(0,N):
                res[i][j] += mat[i][k] * mat[k][j]
  
# Function to check idempotent
# property of matrix.
def checkIdempotent(mat):
  
    N= len(mat)
    # Calculate multiplication of matrix
    # with itself and store it into res.
    res =[[0]*N for i in range(0,N)]
    multiply(mat, res)
  
    for i in range(0,N):
        for j in range(0,N):     
            if (mat[i][j] != res[i][j]):

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#

// C# program to check given matrix 


// is idempotent matrix or not.
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 idempotent
    // property of matrix.
    static bool checkIdempotent(int [,]mat)
    { 
        // Calculate multiplication of matrix
        // with itself and store it into res.
        int [,]res = new int[N,N];
        multiply(mat, res);

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

Program to check if a matrix is


symmetric

Program to check if a matrix is symmetric - GeeksforGeeks


A square matrix is said to be symmetric matrix if the transpose of the matrix is same
as the given matrix. Symmetric matrix can be obtain by changing row to column and
column to row.
Examples:

Input : 1 2 3
2 1 4
3 4 3
Output : Yes

Input : 3 5 8
3 4 7
8 5 3
Output : No

A Simple solution is to do following.


1) Create transpose of given matrix.
2) Check if transpose and given matrices are same or not,

C++

// Simple c++ code for check a matrix is


// symmetric or not.
#include <iostream>
using namespace std;

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

// Simple java code for check a matrix is


// symmetric or not.
  
import java.io.*;
  
class GFG {
      
  
  

1729
Chapter 250. Program to check if a matrix is symmetric

 static int  MAX = 100;


  
// Fills transpose of mat[N][N] in tr[N][N]
 static void transpose(int mat[][], int tr[][], 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
 static boolean isSymmetric(int mat[][], int N)
{
    int tr[][] = new int[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
    public static void main (String[] args)
 {
          
        int mat[][] = { { 1, 3, 5 },
                    { 3, 2, 4 },
                    { 5, 4, 1 } };
  
    if (isSymmetric(mat, 3))
        System.out.println( "Yes");
    else
        System.out.println ( "No");
      
    }
}

Python

# Simple Python code for check a matrix is


# symmetric or not.
   
# Fills transpose of mat[N][N] in tr[N][N]
def transpose(mat, tr, N):
    for i in range(N):
        for j in range(N):
            tr[i][j] = mat[j][i]

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#

// Simple C# code for check a matrix is


// symmetric or not.
  
using System;
  
class GFG {
      
    static int MAX = 100;
      
    // Fills transpose of mat[N][N] in tr[N][N]
    static void transpose(int [,]mat, int [,]tr, 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
    static bool isSymmetric(int [,]mat, int N)
    {
        int [,]tr = new int[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])

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

Time Complexity : O(N x N)


Auxiliary Space : O(N x N)
An Efficient solution to check a matrix is symmetric or not is to compare matrix elements
without creating a transpose. We basically need to compare mat[i][j] with mat[j][i].

C++

// Efficient c++ code for check a matrix is


// symmetric or not.
#include <iostream>
using namespace std;
  
const int MAX = 100;
  
// Returns true if mat[N][N] is symmetric, else false
bool isSymmetric(int mat[][MAX], int 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;
}
  
// Driver code
int main()
{
    int mat[][MAX] = { { 1, 3, 5 },
                       { 3, 2, 4 },
                       { 5, 4, 1 } };

1733
Chapter 250. Program to check if a matrix is symmetric

  
    if (isSymmetric(mat, 3))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Efficient Java code for check a matrix is


// symmetric or no
  
import java.io.*;
  
class GFG {
     
  
static int MAX = 100;
  
// Returns true if mat[N][N]
// is symmetric, else false
 static boolean isSymmetric(int mat[][], int 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;
}
  
// Driver code
      
    public static void main (String[] args)
 {
            int mat[][] = { { 1, 3, 5 },
                    { 3, 2, 4 },
                    { 5, 4, 1 } };
  
    if (isSymmetric(mat, 3))
        System.out.println(  "Yes");
    else
          
        System.out.println("NO");
          
    }
}
// This article is contributed by vt_m.

1734
Chapter 250. Program to check if a matrix is symmetric

Python

# Efficient Python code for check a matrix is


# symmetric or not.
  
# Returns true if mat[N][N] is symmetric, else false
def isSymmetric(mat, N):
    for i in range(N):
        for j in range(N):
            if (mat[i][j] != mat[j][i]):
                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#

// Efficient C# code for check a matrix is


// symmetric or no
  
using System;
  
class GFG 
{
    //static int MAX = 100;
      
    // Returns true if mat[N][N]
    // is symmetric, else false
    static bool isSymmetric(int [,]mat, int 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;
    }
      
    // Driver code
    public static void Main ()
    {

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

Time Complexity : O(N x N)


Auxiliary Space : O(1)
Improved By : jit_t, Sam007

Source

https://www.geeksforgeeks.org/program-to-check-if-a-matrix-is-symmetric/

1737
Chapter 251

Program to check if matrix is


lower triangular

Program to check if matrix is lower triangular - GeeksforGeeks


Given a square matrix and the task is to check the matrix is in lower triangular form or not.
A square matrix is called lower triangular if all the entries above the main diagonal are zero.

Examples:

Input : mat[4][4] = {{1, 0, 0, 0},


{1, 4, 0, 0},
{4, 6, 2, 0},
{0, 4, 7, 6}};
Output : Matrix is in lower triangular form.

Input : mat[4][4] = {{1, 0, 0, 0},


{4, 3, 0, 1},
{7, 9, 2, 0},
{8, 5, 3, 6}};

1738
Chapter 251. Program to check if matrix is lower triangular

Output : Matrix is not in lower triangular form.

C++

// Program to check lower


// triangular matrix.
#include <bits/stdc++.h>
#define N 4
using namespace std;
  
// Function to check matrix is in 
// lower triangular form or not.
bool isLowerTriangularMatrix(int mat[N][N])
{
    for (int i = 0; i < N; i++)
        for (int j = i + 1; j < N; j++)
            if (mat[i][j] != 0)
                return false;
    return true;
}
  
// Driver function.
int main()
{
    int mat[N][N] = { { 1, 0, 0, 0 },
                      { 1, 4, 0, 0 },
                      { 4, 6, 2, 0 },
                      { 0, 4, 7, 6 } };
  
    // Function call
    if (isLowerTriangularMatrix(mat))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Java Program to check for 


// a lower triangular matrix.
import java.io.*;
  
class Lower_triangular
{
    int N = 4;
  

1739
Chapter 251. Program to check if matrix is lower triangular

    // Function to check matrix is 


    // in lower triangular form or not.
    boolean isLowerTriangularMatrix(int mat[][])
    {
        for (int i = 0; i < N; i++)
            for (int j = i + 1; j < N; j++)
                if (mat[i][j] != 0)
                    return false;
  
        return true;
    }
  
    // Driver function.
    public static void main(String args[])
    {
        Lower_triangular ob = new Lower_triangular();
        int mat[][] = { { 1, 0, 0, 0 },
                        { 1, 4, 0, 0 },
                        { 4, 6, 2, 0 },
                        { 0, 4, 7, 6 } };
                          
        // Function call
        if (ob.isLowerTriangularMatrix(mat))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Anshika Goyal.

Python3

# Python3 Program to check 


# lower triangular matrix.
  
# Function to check matrix 
# is in lower triangular
def islowertriangular(M):
    for i in range(0, len(M)):
        for j in range(i + 1, len(M)):
            if(M[i][j] != 0): 
                    return False
    return True
      
# Driver function.
M = [[1,0,0,0],
     [1,4,0,0],

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#

// C# program to check for


// a lower triangular matrix.
using System;
  
class Lower_triangular 
{
    int N = 4;
  
    // Function to check matrix is
    // in lower triangular form or not.
    bool isLowerTriangularMatrix(int[, ] mat)
    {
        for (int i = 0; i < N; i++)
            for (int j = i + 1; j < N; j++)
                if (mat[i, j] != 0)
                    return false;
  
        return true;
    }
  
    // Driver function.
    public static void Main()
    {
        Lower_triangular ob = new Lower_triangular();
        int[, ] mat = { { 1, 0, 0, 0 },
                        { 1, 4, 0, 0 },
                        { 4, 6, 2, 0 },
                        { 0, 4, 7, 6 } };
  
        // Function call
        if (ob.isLowerTriangularMatrix(mat))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}

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

Program to check if matrix is


singular or not

Program to check if matrix is singular or not - GeeksforGeeks


A matrix is said to be singular if the determinant of the matrix is 0 otherwise it is non-
singular .
Examples:

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++

// C++ program check if a matrix is


// singular or not.
#include <bits/stdc++.h>

1743
Chapter 252. Program to check if matrix is singular or not

using namespace std;


#define N 4
  
// Function to get cofactor of mat[p][q] in temp[][].
// n is current dimension of mat[][]
void getCofactor(int mat[N][N], int temp[N][N], 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 to check if mat[][] is
   singular or not. */
bool isSingular(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++) {
  

1744
Chapter 252. Program to check if matrix is singular or not

        // Getting Cofactor of mat[0][f]


        getCofactor(mat, temp, 0, f, n);
        D += sign * mat[0][f] * isSingular(temp, n - 1);
  
        // terms are to be added with alternate sign
        sign = -sign;
    }
  
    return D;
}
  
// Driver program to test above functions
int main()
{
    int mat[N][N] = { { 4, 10, 1 },
                      { 0, 0, 0 },
                      { 1, 4, -3 } };
    if (isSingular(mat, N))
        cout << "Matrix is Singular" << endl;
    else
        cout << "Matrix is non-singular" << endl;
    return 0;
}

Output:

Matrix is non-singular

Source

https://www.geeksforgeeks.org/program-check-matrix-singular-not/

1745
Chapter 253

Program to check if matrix is


upper triangular

Program to check if matrix is upper triangular - GeeksforGeeks


Given a square matrix and the task is to check the matrix is in upper triangular form or
not. A square matrix is called upper triangular if all the entries below the main diagonal
are zero.

Examples:

Input : mat[4][4] = {{1, 3, 5, 3},


{0, 4, 6, 2},

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.

Input : mat[4][4] = {{5, 6, 3, 6},


{0, 4, 6, 6},
{1, 0, 8, 5},
{0, 1, 0, 6}};
Output : Matrix is not in Upper Triangular form.

C++

// Program to check upper triangular matrix.


#include <bits/stdc++.h>
#define N 4
using namespace std;
  
// Function to check matrix is in upper triangular
// form or not.
bool isUpperTriangularMatrix(int mat[N][N])
{
    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.
int main()
{
    int mat[N][N] = { { 1, 3, 5, 3 },
                      { 0, 4, 6, 2 },
                      { 0, 0, 2, 5 },
                      { 0, 0, 0, 6 } };
    if (isUpperTriangularMatrix(mat))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Java Program to check upper 


// triangular matrix.
import java.util.*;

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

# Python3 Program to check upper 


# triangular matrix.
  
# Function to check matrix 
# is in upper triangular
def isuppertriangular(M):
    for i in range(1, len(M)):
        for j in range(0, i):
            if(M[i][j] != 0): 
                    return False
    return True
      
# Driver function.

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#

// C# Program to check upper 


// triangular matrix.
using System;
  
public class GfG
{
    private static int N = 4;
  
    // Function to check matrix is in
    // upper triangular form or not.
    public static bool 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(){
        int [,]mat= { { 1, 3, 5, 3 },
                    { 0, 4, 6, 2 },
                    { 0, 0, 2, 5 },
                    { 0, 0, 0, 6 } };
                      
        if (isUpperTriangularMatrix(mat))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
/* This code is contributed by vt_m */

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

Program to check if two given


matrices are identical

Program to check if two given matrices are identical - GeeksforGeeks


The below program checks if two square matrices of size 4*4 are identical or not.For any
two matrix to be equal, number of rows and columns in both the matrix should be equal
and the corresponding elements should also be equal.
C

#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

    int B[N][N] = { {1, 1, 1, 1},


                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};
  
    if (areSame(A, B))
        printf("Matrices are identical");
    else
        printf("Matrices are not identical");
    return 0;
}

Java

// Java Program to check if two 


// given matrices are identical
  
class GFG
{
    static final int N = 4;
      
    // This function returns 1 if A[][] 
    // and B[][] are identical
    // otherwise returns 0
    static int areSame(int A[][], int B[][])
    {
        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;
    }
      
    // 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[][] = { {1, 1, 1, 1},
                      {2, 2, 2, 2},
                      {3, 3, 3, 3},
                      {4, 4, 4, 4}};
      
        if (areSame(A, B) == 1)

1752
Chapter 254. Program to check if two given matrices are identical

            System.out.print("Matrices are identical");


        else
            System.out.print("Matrices are not identical");
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Program to check if two


# given matrices are identical
  
N = 4
   
# This function returns 1
# if A[][] and B[][] are identical
# otherwise returns 0
def areSame(A,B):
      
    for i in range(N):
        for j in range(N):
            if (A[i][j] != B[i][j]):
                return 0
    return 1
  
# driver code
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]]
                      
if (areSame(A, B)==1):
    print("Matrices are identical")
else:
    print("Matrices are not identical")
  
# This code is contributed
# by Anant Agarwal.

C#

// C# Program to check if two 

1753
Chapter 254. Program to check if two given matrices are identical

// given matrices are identical


using System;
  
class GFG {
      
    static int N = 4;
      
    // This function returns 1 if A[][] 
    // and B[][] are identical
    // otherwise returns 0
    static int areSame(int [,]A, int [,]B)
    {
        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;
    }
      
    // 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 = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};
      
        if (areSame(A, B) == 1)
            Console.WriteLine("Matrices "
                      + "are identical");  
        else
            Console.WriteLine("Matrices "
                  + "are not identical");
    }
}
  
// This code is contributed by anuj_67.

PHP

<?php
// PHP Program to check if two

1754
Chapter 254. Program to check if two given matrices are identical

// given matrices are identical


  
// function returns 1 if A[][] 
// and B[][] are identical
// otherwise returns 0
function areSame($A, $B)
{
  
    for($i = 0; $i < 4; $i++)
        for ($j = 0; $j < 4; $j++)
            if ($A[$i][$j] != $B[$i][$j])
                return 0;
    return 1;
}
  
// Driver Code
$A = array(array(1, 1, 1, 1),
           array(2, 2, 2, 2),
           array(3, 3, 3, 3),
           array(4, 4, 4, 4));
  
$B = array(array(1, 1, 1, 1),
           array(2, 2, 2, 2),
           array(3, 3, 3, 3),
           array(4, 4, 4, 4)); 
  
    if (areSame($A, $B) == 1)
        echo "Matrices are identical";
    else
        echo "Matrices are not identical";
          
// This code is contributed by Anuj_67
?>

Output:

Matrices are identical

The program can be extended for rectangular matrices. The following post can be useful
for extending this program.

How to pass a 2D array as a parameter in C?


The time complexity of the above program is O(n2 ).
Improved By : vt_m

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

Program to find Normal and


Trace of a matrix

Program to find Normal and Trace of a matrix - GeeksforGeeks


Given a 2D matrix, the task is to find Trace and Normal of matrix.
Normal of a matrix is defined as square root of sum of squares of matrix elements.
Trace of a n x n square matrix is sum of diagonal elements.
Examples :

Input : mat[][] = {{7, 8, 9},


{6, 1, 2},
{5, 4, 3}};
Output : Normal = 16
Trace = 11
Explanation :
Normal = sqrt(7*7+ 8*8 + 9*9 + 6*6 +
1*1 + 2*2 + 5*5 + 4*4 + 3*3)
= 16
Trace = 7+1+3 = 11

Input :mat[][] = {{1, 2, 3},


{6, 4, 5},
{2, 1, 3}};
Output : Normal = 10
Trace = 8
Explanation :
Normal = sqrt(1*1 +2*2 + 3*3 + 6*6 + 4*4 +
5*5 + 2*2 + 1*1 + 3*3)
Trace = 8(1+4+3)

1757
Chapter 255. Program to find Normal and Trace of a matrix

CPP

// C++ program to find trace and normal


// of given matrix
#include<bits/stdc++.h>
using namespace std;
  
// Size of given matrix
const int MAX = 100;
  
// Returns Normal of a matrix of size n x n
int findNormal(int mat[][MAX], int n)
{
    int sum = 0;
    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            sum += mat[i][j]*mat[i][j];
    return sqrt(sum);
}
  
// Returns trace of a matrix of size n x n
int findTrace(int mat[][MAX], int n)
{

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

// Java program to find trace and normal


// of given matrix
  
import java.io.*;
  
class GFG {
  
// Size of given matrix
static  int MAX = 100;
  
// Returns Normal of a matrix of size n x n
 static int findNormal(int mat[][], int n)
{
    int sum = 0;
    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            sum += mat[i][j]*mat[i][j];
    return (int)Math.sqrt(sum);
}
  
// Returns trace of a matrix of size n x n
 static int findTrace(int mat[][], int n)
{
    int sum = 0;

1759
Chapter 255. Program to find Normal and Trace of a matrix

    for (int i=0; i<n; i++)


        sum += mat[i][i];
    return sum;
}
  
// Driven source
public static void main (String[] args) {
  
            int mat[][] = {{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},
    };
  
    System.out.println ("Trace of Matrix = "
         + findTrace(mat, 5));
    System.out.println ("Normal of Matrix = "
         + findNormal(mat, 5));
          
    }

  
// This code is contributed by vt_m.

C#

// C# program to find trace and normal


// of given matrix
using System;
  
class GFG {
      
    // Returns Normal of a matrix of
    // size n x n
    static int findNormal(int [,]mat, int n)
    {
        int sum = 0;
          
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                sum += mat[i,j] * mat[i,j];
                  
        return (int)Math.Sqrt(sum);
    }
      
    // Returns trace of a matrix of size 
    // n x n

1760
Chapter 255. Program to find Normal and Trace of a matrix

    static int findTrace(int [,]mat, int n)


    {
        int sum = 0;
          
        for (int i = 0; i < n; i++)
            sum += mat[i,i];
              
        return sum;
    }
      
    // Driven source
    public static void Main () 
    {
        int [,]mat = { {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},
    };
  
    Console.Write ("Trace of Matrix = "
            + findTrace(mat, 5) + "\n");
    Console.Write("Normal of Matrix = "
                    + findNormal(mat, 5));
          
    }

  
// This code is contributed by nitin mittal.

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

Time Complexity : O(n*n)


Space Complexity : O(1)
References:
https://en.wikipedia.org/wiki/Trace_(linear_algebra)
Improved By : nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/program-find-normal-trace-matrix/

1762
Chapter 256

Program to find all types of


Matrix

Program to find all types of Matrix - GeeksforGeeks


Given the dimension of the matrix R(rows) * C(column) the task is to find which type of
matrix is representing by the given dimension.
Examples:

Input : R = 1 C = 0
Output : Row Matrix

Input : R = 4 C = 5
Output : Horizontal Matrix

• Row Matrix : When R = 1 and C = 0 then the matrix represent Row


Matrix .
• Column Matrix : When C = 1 and R = 0 then the matrix represent
Column Matrix.
• Horizontal Matrix : A Matrix in which number of rows is smaller than
the number of column is called Horizontal Matrix (R < C) .
• Vertical Matrix : A Matrix in which number of rows is greater than the
number of column is called Horizontal Matrix (R > C).
• Square Matrix : A matrix in which number of rows is equal to number
of column is called Square Matrix (R = C).

C++

// C++ program to check 


// types of Matrix

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

// Java program to check 


// types of Matrix
import java.io.*;
import java.util.*;
import java.math.*;
import java.util.regex.*;
  
public class GFG {
  
    // Fuction to display which type of matrix
    static void check(int r, int c)
    {
        if (r == 0 && c == 1)

1764
Chapter 256. Program to find all types of Matrix

            System.out.println("Column Matrix ");


        else if (r == 1 && c == 0)
            System.out.println("Row Matrix ");
        else if (r < c)
            System.out.println("Horizontal Matrix ");
        else if (r > c)
            System.out.println("Vertical Matrix ");
        else if (r == c)
            System.out.println("Square Matrix ");
    }
  
    // Driver code
    public static void main(String[] args) 
    {
  
        // static input for r and c
        // function calling
        check(1, 0);
        check(0, 1);
        check(4, 5);
        check(5, 4);
        check(3, 3);
    }
}

Python3

# Python3 program to check


# types of Matrix
  
  
# Fuction to display which 
# type of matrix
def check(r, c) :
      
  
    if r == 0 and c == 1:
        print ("Column Matrix ")
          
    elif r == 1 and c == 0:
        print ("Row Matrix ") 
      
    elif r < c:
        print ("Horizontal Matrix ") 
          
    elif r > c:
        print ("Vertical Matrix ") 
          

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#

// C# program to check types of Matrix


using System;
  
class GFG
{
    // Fuction to display which type of matrix
    static void check(int r, int c)
    {
        if (r == 0 && c == 1)
            Console.WriteLine("Column Matrix ");
        else if (r == 1 && c == 0)
            Console.WriteLine("Row Matrix ");
        else if (r < c)
            Console.WriteLine("Horizontal Matrix ");
        else if (r > c)
            Console.WriteLine("Vertical Matrix ");
        else if (r == c)
            Console.WriteLine("Square Matrix ");
    }
  
    // Driver code
    static void Main() 
    {
  
        // static input for r and c
        // function calling
        check(1, 0);
        check(0, 1);
        check(4, 5);
        check(5, 4);
        check(3, 3);
    }

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

Program to find largest element


in an array

Program to find largest element in an array - GeeksforGeeks


Given an array, find the largest element in it.
Example:

Input : arr[] = {10, 20, 4}


Output : 20

Input : arr[] = {20, 10, 20, 4, 100}


Output : 100

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++

// C++ program to find maximum


// in arr[] of size n 
#include <bits/stdc++.h>
using namespace std;
  
int largest(int arr[], int n)
{
    int i;
      
    // Initialize maximum element

1769
Chapter 257. Program to find largest element in an array

    int 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
int main()
{
    int arr[] = {10, 324, 45, 90, 9808};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Largest in given array is " 
         << largest(arr, n);
    return 0;
}
  
// This Code is contributed 
// by Shivi_Aggarwal

// C program to find maximum in arr[] of size n 


#include <stdio.h>
  
// C function to find maximum in arr[] of size n
int largest(int arr[], int n)
{
    int i;
     
    // Initialize maximum element
    int 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;
}
  
int main()

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

// Java Program to find maximum in arr[] 


class Test
{
     static int arr[] = {10, 324, 45, 90, 9808};
       
     // Method to find maximum in arr[]
     static int largest()
     {
         int i;
           
         // Initialize maximum element
         int max = arr[0];
        
         // Traverse array elements from second and
         // compare every element with current max  
         for (i = 1; i < arr.length; i++)
             if (arr[i] > max)
                 max = arr[i];
        
         return max;
     }
       
     // Driver method
     public static void main(String[] args) 
     {
         System.out.println("Largest in given array is " + largest());
        }
 }

Python3

# Python3 program to find maximum


# in arr[] of size n 
  
# python function to find maximum
# in arr[] of size n
def largest(arr,n):
  

1771
Chapter 257. Program to find largest element in an array

    # Initialize maximum element


    max = arr[0]
  
    # Traverse array elements from second
    # and compare every element with 
    # current max
    for i in range(1, n):
        if arr[i] > max:
            max = arr[i]
    return max
  
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr,n)
print ("Largest in given array is",Ans)
  
# This code is contributed by Smitha Dinesh Semwal

C#

// C# Program to find maximum in arr[] 


using System;
  
class GFG {
      
    static int []arr = {10, 324, 45, 90, 9808};
      
    // Method to find maximum in arr[]
    static int largest()
    {
        int i;
          
        // Initialize maximum element
        int max = arr[0];
      
        // Traverse array elements from second and
        // compare every element with current max 
        for (i = 1; i < arr.Length; i++)
            if (arr[i] > max)
                max = arr[i];
      
        return max;
    }
      
    // Driver method
    public static void Main() 
    {

1772
Chapter 257. Program to find largest element in an array

        Console.WriteLine("Largest in given "


                  + "array is " + largest());
    }
}
  
// This code is contributed by anuj_67.

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:

Largest in given array is 9808

1773
Chapter 257. Program to find largest element in an array

Using Library Function :


We use std::max_element in C++.
C++

// C++ program to find maximum in arr[] of size n 


#include <bits/stdc++.h>
using namespace std;
  
// returns maximum in arr[] of size n
int largest(int arr[], int n)
{
    return *max_element(arr, arr+n);
}
  
int main()
{
    int arr[] = {10, 324, 45, 90, 9808};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << largest(arr, n);
    return 0;
}

Java

// Java program to 


// find maximum in
// arr[] of size n
import java .io.*;
import java.util.*;
  
class GFG
{
      
    // returns maximum in
    // arr[] of size n
    static int largest(int []arr,   
                       int n)
    {
        Arrays.sort(arr);
        return arr[n - 1];
    }
  
    // Driver code
    static public void main (String[] args)
    {
        int []arr = {10, 324, 45, 
                     90, 9808};

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

# Python 3 program to find


# maximum in arr[] of size n 
  
# returns maximum
# in arr[] of size n
def largest(arr, n):
  
    return max(arr)
  
# driver code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
  
print(largest(arr, n))
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# program to find maximum in


// arr[] of size n
using System;
using System.Linq;
  
public class GFG {
      
    // returns maximum in arr[] of size n
    static int largest(int []arr, int n)
    {
        return arr.Max();
    }
  
    // Driver code
    static public void Main ()
    {
        int []arr = {10, 324, 45, 90, 9808};

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

Time complexity of the above solution is .


Refer below article for more methods.
Program to find the minimum (or maximum) element of an array
Improved By : jit_t, vt_m, Shivi_Aggarwal

Source

https://www.geeksforgeeks.org/c-program-find-largest-element-array/

1776
Chapter 258

Program to find transpose of a


matrix

Program to find transpose of a matrix - GeeksforGeeks


Transpose of a matrix is obtained by changing rows to columns and columns to rows. In
other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].

For Square Matrix :


The below program finds transpose of A[][] and stores the result in B[][], we can change N
for different dimension.

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

void transpose(int A[][N], int B[][N])


{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            B[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}};
  
    int B[N][N], i, j;
  
    transpose(A, B);
  
    printf("Result matrix is \n");
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < N; j++)
           printf("%d ", B[i][j]);
        printf("\n");
    }
  
    return 0;
}

Java

// Java Program to find 


// transpose of a matrix
  
class GFG
{
    static final 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];
    }

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

# Python3 Program to find


# transpose of a matrix
  
N = 4
   
# This function stores
# transpose of A[][] in B[][]
  
def transpose(A,B):
  
    for i in range(N):
        for j in range(N):
            B[i][j] = A[j][i]
  
# driver code
A = [ [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]]
   
   

1779
Chapter 258. Program to find transpose of a matrix

B = A[:][:] # To store result


  
transpose(A, B)
   
print("Result matrix is")
for i in range(N):
    for j in range(N):
        print(B[i][j], " ", end='')
    print()
      
# This code is contributed
# by Anant Agarwal.

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

For Rectangular Matrix :


The below program finds transpose of A[][] and stores the result in B[][].
C++

#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

// Java Program to find 


// transpose of a matrix
  
class GFG
{
    static final int M = 3;
    static final 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 (String[] args)
    {
        int A[][] = { {1, 1, 1, 1},
                      {2, 2, 2, 2},
                      {3, 3, 3, 3}};
      
        int B[][] = new int[N][M], i, j;
      
        transpose(A, B);
      
        System.out.print("Result matrix is \n");
        for (i = 0; i < N; i++)
        {
            for (j = 0; j < M; j++)
            System.out.print(B[i][j] + " ");

1782
Chapter 258. Program to find transpose of a matrix

            System.out.print("\n");
        }
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 Program to find


# transpose of a matrix
  
M = 3
N = 4
  
# This function stores
# transpose of A[][] in B[][]
  
def transpose(A, B):
  
    for i in range(N):
        for j in range(M):
            B[i][j] = A[j][i]
  
# driver code
A = [ [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3]]
  
  
# To store result
B = [[0 for x in range(M)] for y in range(N)] 
  
transpose(A, B)
  
print("Result matrix is")
for i in range(N):
    for j in range(M):
        print(B[i][j], " ", end='')
    print()    

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

In-Place for Square Matrix:

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

// Java Program to find 


// transpose of a matrix
  
class GFG
{
    static final int N = 4;
      
    // Finds transpose of A[][] in-place
    static void transpose(int A[][])
    {

1785
Chapter 258. Program to find transpose of a matrix

        for (int i = 0; i < N; i++)


            for (int j = i+1; j < N; j++)
            {
                 int temp = A[i][j];
                 A[i][j] = A[j][i];
                 A[j][i] = temp;
            }
    }
      
    // 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}};
         
        transpose(A);
      
        System.out.print("Modified matrix is \n");
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            System.out.print(A[i][j] + " ");
            System.out.print("\n");
        }
    }
}

Python3

# Python3 Program to find


# transpose of a matrix
  
N = 4
   
# Finds transpose of A[][] in-place
def transpose(A):
  
    for i in range(N):
        for j in range(i+1, N):
            A[i][j], A[j][i] = A[j][i], A[i][j]
  
# driver code
A = [ [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]]

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#

// C# Program to find transpose of


// a matrix
using System;
  
class GFG {
      
    static int N = 4;
      
    // Finds transpose of A[][] in-place
    static void transpose(int [,]A)
    {
        for (int i = 0; i < N; i++)
            for (int j = i+1; j < N; j++)
            {
                int temp = A[i,j];
                A[i,j] = A[j,i];
                A[j,i] = temp;
            }
    }
      
    // Driver code
    public static void Main ()
    {
        int [,]A = { {1, 1, 1, 1},
                    {2, 2, 2, 2},
                    {3, 3, 3, 3},
                    {4, 4, 4, 4}};
          
        transpose(A);
      
        Console.WriteLine("Modified matrix is ");
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)

1787
Chapter 258. Program to find transpose of a matrix

                Console.Write(A[i,j] + " ");


                  
            Console.WriteLine();
        }
    }
}
  
// This code is contributed by anuj_67.

Output:

Modified matrix is
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

Improved By : AbhijeetPrakash, nitin mittal, vt_m

Source

https://www.geeksforgeeks.org/program-to-find-transpose-of-a-matrix/

1788
Chapter 259

Program to multiply two


matrices

Program to multiply two matrices - GeeksforGeeks


Given two matrices, the task to to multiply them. Matrices can either be square or rectan-
gular.
Examples:

Input : mat1[][] = {{1, 2},


{3, 4}}
mat2[][] = {{1, 1},
{1, 1}}
Output : {{3, 3},
{7, 7}}
Input : mat1[][] = {{2, 4},
{3, 4}}
mat2[][] = {{1, 2},
{1, 3}}
Output : {{6, 16},
{7, 18}}

1789
Chapter 259. Program to multiply two matrices

Multiplication of Square Matrices :


The below program multiplies two square matrices of size 4*4, we can change N for different
dimension.
C++
// C++ program to multiply
// two square matrices.
#include
using namespace std;
#define N 4
// This function multiplies
// mat1[][] and mat2[][], and
// stores the result in res[][]
void multiply(int mat1[][N],
int mat2[][N],
int res[][N])
{
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 int main() { int i, j; int res[N][N];
// To store result 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}}; multiply(mat1, mat2,
res); cout << ”Result matrix is \n”; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout
<< res[i][j] << ” ”; cout << ”\n”; } return 0; } // This code is contributed // by Soumik
Mondal [tabby title=”C”]

// C program to multiply two square matrices.


#include <stdio.h>
#define N 4
  
// This function multiplies mat1[][] and mat2[][],
// and stores the result in res[][]
void multiply(int mat1[][N], int mat2[][N], int res[][N])

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

// Java program to multiply two square


// matrices.
import java.io.*;
  
class GFG {
      

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#

// C# program to multiply two square


// matrices.
using System;
  
class GFG {
      
  
    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 () 
    {
        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}};

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

Multiplication of Rectangular Matrices :


We use pointers in C to multiply to matrices. Please refer the following post as a prerequisite
of the code.
How to pass a 2D array as a parameter in C?

// C program to multiply two rectangular matrices


#include<stdio.h>
  
// Multiplies two matrices mat1[][] and mat2[][]
// and prints result.
// (m1) x (m2) and (n1) x (n2) are dimensions
// of given matrices.
void multiply(int m1, int m2, int mat1[][m2],
              int n1, int n2, int mat2[][n2])
{
    int x, i, j;

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

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++

// C++ program to print Lower 


// triangular and Upper triangular
// matrix of an array
#include<iostream>
  
using namespace std;
  
// Function to form 
// lower triangular matrix
void lower(int matrix[3][3], int row, int col)
{
    int i, j;
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
            if (i < j)
            {
                cout << "0" << " ";
            }
            else
            cout << matrix[i][j] << " ";
        }

1798
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array

        cout << endl;


    }
}
  
// Function to form upper triangular marix
void upper(int matrix[3][3], int row, int col)
{
    int i, j;
      
    for (i = 0; i < row; i++)
    {
        for (j = 0; j < col; j++)
        {
            if (i > j)
            {
                cout << "0" << " ";
            }
            else
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
}
  
// Driver Code
int main()
{
    int matrix[3][3] = {{1, 2, 3}, 
                        {4, 5, 6}, 
                        {7, 8, 9}};
    int row = 3, col = 3;
      
    cout << "Lower triangular matrix: \n";
    lower(matrix, row, col);
      
    cout << "Upper triangular matrix: \n";
    upper(matrix, row, col);
          
    return 0;
}

Java

// Java program to print Lower 


// triangular and Upper triangular
// matrix of an array
class GFG
{

1799
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array

    // 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)
                {
                    System.out.print("0" + " ");
                }
                else
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
      
    // Method to form upper
    // triangular matrix
    static void upper(int matrix[][], 
                      int row, int col)
    {
        int i, j;
        for (i = 0; i < row; i++)
        {
            for (j = 0; j < col; j++)
            {
                if (i > j)
                {
                    System.out.print("0" + " ");
                }
                else
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
       
    // Driver Code
    public static void main(String args[])
    {
        int matrix[][] = {{1, 2, 3}, 
                          {4, 5, 6}, 
                          {7, 8, 9}};

1800
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array

        int row = 3, col = 3;


          
        System.out.println("Lower triangular matrix: ");
        lower(matrix, row, col);
          
        System.out.println("Upper triangular matrix: ");
        upper(matrix, row, col);
    }
}

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

            if ($i < $j)


            {
                echo "0" , " ";
            }
            else
            echo $matrix[$i][$j] , " ";
        }
        echo "\n";
    }
}
  
// Function to form
// upper triangular marix
function upper($matrix, $row, $col)
{
    $i; $j;
      
    for ($i = 0; $i < $row; $i++)
    {
        for ($j = 0; $j < $col; $j++)
        {
            if ($i > $j)
            {
                echo "0" , " ";
            }
            else
            echo $matrix[$i][$j] ," ";
        }
    echo "\n";
    }
}
  
// Driver Code
$matrix = array (array (1, 2, 3),
                  array (4, 5, 6),
                 array (7, 8, 9));
$row = 3; $col = 3;
  
echo "Lower triangular matrix: \n";
lower($matrix, $row, $col);
  
echo "Upper triangular matrix: \n";
upper($matrix, $row, $col);
      
// This code is contributed by jit_t
?>

Output :

1803
Chapter 260. Program to print Lower triangular and Upper triangular matrix of an array

Lower triangular matrix:


1 0 0
4 5 0
7 8 9
Upper triangular matrix:
1 2 3
0 5 6
0 0 9

Improved By : jit_t

Source

https://www.geeksforgeeks.org/program-print-lower-triangular-upper-triangular-matrix-array/

1804
Chapter 261

Program to print numbers in


digital form

Program to print numbers in digital form - GeeksforGeeks


Given a number n then print number in Digital form.
Examples :

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++

//  C++ profgram to print 


// number in digital form
#include <iostream>
#include <vector>
using namespace std;
  
// Function to print numbers
void print(int mat[][5])
{
  
    // 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)
                    cout << "-";
                else
                    cout << " ";
            }
            else {
                if (mat[i][j] == 1)
                    cout << "|";
                else
                    cout << " ";
            }
        }
        cout << endl;
    }
}
void digit0()
{
    // 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, 0, 0, 0, 0 },
                    { 1, 0, 0, 0, 1 },
                    { 0, 1, 0, 1, 0 } };
    print(mat);
}
void digit1()
{
    // In matrix 0 used for space
    // and 1 for either - or |
    int mat[5][5] = { { 0, 0, 0, 0, 0 },

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

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();
}
  
// Driver program
int main()
{
    // Input a number
    int num = 9;

1809
Chapter 261. Program to print numbers in digital form

  
    // function call to check digit
    checkDigit(num);
  
    return 0;
}

Java

// Java profgram to print 


// number in digital form
import java.io.*;
  
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)
                        System.out.print("-");
                    else
                        System.out.print(" ");
                }
                else {
                    if (mat[i][j] == 1)
                        System.out.print("|");
                    else
                        System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
    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);

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

        // 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
        // and 1 for either - or |
        int mat[][] = { { 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);
    }
    static void digit8()
    {
        // In matrix 0 used for space
        // and 1 for either - or |
        int mat[][] = { { 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);
    }
    static void digit9()
    {
        // In matrix 0 used for space
        // and 1 for either - or |
        int mat[][] = { { 0, 1, 0, 1, 0 },
                        { 1, 0, 0, 0, 1 },
                        { 0, 1, 0, 1, 0 },

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

        // and 1 for either - or |


        int [ ,]mat = { { 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);
    }
      
    static void digit8()
    {
          
        // In matrix 0 used for space
        // and 1 for either - or |
        int [ ,]mat = { { 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);
    }
      
    static void digit9()
    {
          
        // In matrix 0 used for space
        // and 1 for either - or |
        int [ ,]mat = { { 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
    static void checkDigit(int num)
    {
          
        // for digit 0
        if (num == 0)
            digit0();
      
        // for digit 1
        else if (num == 1)
            digit1();
      
        // for digit 2

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:

- -
| |
- -
|
- -

Improved By : Mithun Kumar

Source

https://www.geeksforgeeks.org/print-numbers-digital-form/

1823
Chapter 262

Program to swap upper


diagonal elements with lower
diagonal elements of matrix.

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.

Below is the implementation of above idea :

C++

// CPP Program to implement matrix


// for swapping the upper diagonal
// elements with lower diagonal 
// elements of matrix.
#include <bits/stdc++.h>
#define n 4
using namespace std;
  
// Function to swap the diagonal 
// elements in a matrix.
void swapUpperToLower(int arr[n][n])
{
    // Loop for swap the elements of matrix.
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int temp = arr[i][j];
            arr[i][j] = arr[j][i];
            arr[j][i] = temp;
        }
    }
      
    // Loop for print the matrix elements.
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << arr[i][j] << " ";
        cout << endl;
    }
}
  
// Driver function to run the program
int main()
{
    int arr[n][n] = { { 2, 3, 5, 6 },
                    { 4, 5, 7, 9 },
                    { 8, 6, 4, 9 },
                    { 1, 3, 5, 6 } };
  
    // Function call
    swapUpperToLower(arr);
    return 0;
}
  
}

1825
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.

Java

// java Program to implement matrix


// for swapping the upper diagonal
// elements with lower diagonal 
// elements of matrix.
import java.io.*;
  
class GFG
{
    static int n = 4;
      
    // Function to swap the diagonal 
    // elements in a matrix.
    static void swapUpperToLower(int arr[][])
    {
        // Loop for swap the elements of matrix.
        for (int i = 0; i < n; i++) 
        {
            for (int j = i + 1; j < n; j++) 
            {
                int temp = arr[i][j];
                arr[i][j] = arr[j][i];
                arr[j][i] = temp;
            }
        }
          
        // Loop for print the matrix elements.
        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[][] = { { 2, 3, 5, 6 },
                        { 4, 5, 7, 9 },
                        { 8, 6, 4, 9 },
                        { 1, 3, 5, 6 } };
  
        // Function call
        swapUpperToLower(arr);
              

1826
Chapter 262. Program to swap upper diagonal elements with lower diagonal elements of
matrix.

    }
}
  
// This code is contributed by vt_m.

C#

// C# Program to implement matrix


// for swapping the upper diagonal
// elements with lower diagonal 
// elements of matrix.
using System;
  
class GFG
{
    static int n = 4;
      
    // Function to swap the diagonal 
    // elements in a matrix.
    static void swapUpperToLower(int [,]arr)
    {
        // Loop for swap the elements of matrix.
        for (int i = 0; i < n; i++) 
        {
            for (int j = i + 1; j < n; j++) 
            {
                int temp = arr[i, j];
                arr[i, j] = arr[j, i];
                arr[j, i] = temp;
            }
        }
          
        // Loop for print the matrix elements.
        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 () 
    {
        int [,]arr = {{ 2, 3, 5, 6 },
                      { 4, 5, 7, 9 },
                      { 8, 6, 4, 9 },

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

Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/program-swap-upper-diagonal-elements-lower-diagonal-elements-matrix/

1829
Chapter 263

Python Counter| Find duplicate


rows in a binary matrix

Python Counter| Find duplicate rows in a binary matrix - GeeksforGeeks


Given a binary matrix whose elements are only 0 and 1, we need to print the rows which
are duplicate of rows which are already present in the matrix.
Examples:

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]]

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.

# Function to find duplicate rows in a binary matrix


from collections import Counter

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

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:

Input : 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]]

Output: Matrices are identical

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.

# Function to check if two given matrices are identical


  
def identicalMatrices(A,B):
  

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:

Matrices are identical

Source

https://www.geeksforgeeks.org/python-list-equality-program-check-two-given-matrices-identical/

1833
Chapter 265

Python heapq to find K’th


smallest element in a 2D array

Python heapq to find K’th smallest element in a 2D array - GeeksforGeeks


Given an n x n matrix and integer k. Find the k’th smallest element in the given 2D array.
Examples:

Input : mat = [[10, 25, 20, 40],


[15, 45, 35, 30],
[24, 29, 37, 48],
[32, 33, 39, 50]]
k = 7
Output : 7th smallest element is 30

We will use similar approach like K’th Smallest/Largest Element in Unsorted Array to solve
this problem.

1. Create an empty min heap using heapq in python.


2. Now assign first row (list) in result variable and convert result list into min heap using
heapify method.
3. Now traverse remaining row elements and push them into created min heap.
4. Now get k’th smallest element using nsmallest(k, iterable) method of heapq module.

# Function to find K'th smallest element in 


# a 2D array in Python
import heapq
  
def kthSmallest(input):
  

1834
Chapter 265. Python heapq to find K’th smallest element in a 2D array

    # assign first row to result variable


    # and convert it into min heap
    result = input[0] 
    heapq.heapify(result)
  
    # now traverse remaining rows and push
    # elements in min heap
    for row in input[1:]:
         for ele in row:
              heapq.heappush(result,ele)
  
    # get list of first k smallest element because
    # nsmallest(k,list) method returns first k 
    # smallest element now print last element of 
    # that list
    kSmallest = heapq.nsmallest(k,result)
    print (k,"th smallest element is ",kSmallest[-1])
  
# Driver program
if __name__ == "__main__":
    input = [[10, 25, 20, 40],
           [15, 45, 35, 30],
           [24, 29, 37, 48],
           [32, 33, 39, 50]]
    k = 7
    kthSmallest(input)

Output:

7th smallest element is 30

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

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.

# Function to find the row with maximum number of 1's


def maxOnes(input):
  
     # map sum function on each row of
     # given matrix
     # it will return list of sum of all one's

1836
Chapter 266. Python map function to find row with maximum number of 1’s

     # in each row, then find index of maximum element


     result = list(map(sum,input))
     print (result.index(max(result)))
  
# Driver program
if __name__ == "__main__":
    input = [[0, 1, 1, 1],[0, 0, 1, 1],[1, 1, 1, 1],[0, 0, 0, 0]]
    maxOnes(input)

Complexity : O(M*N)
Output:

Source

https://www.geeksforgeeks.org/python-map-function-find-row-maximum-number-1s/

1837
Chapter 267

Python program to add two


Matrices

Python program to add two Matrices - GeeksforGeeks


Aim : Program to compute the sum of two matrices and then print it in Python.
Examples:

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]]

We can perform matrix addition in following ways in Python.

1. Using for loop:

# Program to add two matrices using nested loop


  
X = [[1,2,3],
    [4 ,5,6],

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:

[10, 10, 10]


[10, 10, 10]
[10, 10, 10]

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.

# Program to add two matrices


# using list comprehension
   
X = [[1,2,3],
    [4 ,5,6],
    [7 ,8,9]]
   
Y = [[9,8,7],
    [6,5,4],
    [3,2,1]]
  
result = [[X[i][j] + Y[i][j]  for j in range

1839
Chapter 267. Python program to add two Matrices

(len(X[0]))] for i in range(len(X))]


   
for r in result:
    print(r)

Output:

[10, 10, 10]


[10, 10, 10]
[10, 10, 10]

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

# Program to add two matrices


# using zip()
   
X = [[1,2,3],
    [4 ,5,6],
    [7 ,8,9]]
   
Y = [[9,8,7],
    [6,5,4],
    [3,2,1]]
  
result = [map(sum, zip(*t)) for t in zip(X, Y)]
   
print(result)

Output:

[[10, 10, 10], [10, 10, 10], [10, 10, 10]]

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

Python program to multiply


two matrices

Python program to multiply two matrices - GeeksforGeeks


Given two matrix the task is that we will have to create a program to multiply two matrices
in python.
Examples:

Input : X = [[1, 7, 3],


[3, 5, 6],
[6, 8, 9]]
Y = [[1, 1, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

Output : [55, 65, 49, 5]


[57, 68, 72, 12]
[90, 107, 111, 21]

Using Simple Nested Loops


In this program we have to use nested for loops to iterate through each row and each column.

# Program to multiply two matrices using nested loops


  
# take a 3x3 matrix
A = [[12, 7, 3],
    [4, 5, 6],
    [7, 8, 9]]
  
# take a 3x4 matrix    

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:

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

Method 2: Matrix Multiplication Using Nested List. We use zip in Python.

# Program to multiply two matrices using list comprehension


  
# take a 3x3 matrix
A = [[12, 7, 3],
    [4, 5, 6],
    [7, 8, 9]]
  
# take a 3x4 matrix
B = [[5, 8, 1, 2],
    [6, 7, 3, 0],
    [4, 5, 9, 1]]
  
# result will be 3x4
result = [[sum(a * b for a, b in zip(A_row, B_col)) 
                        for B_col in zip(*B)]
                                for A_row in A]
  

1842
Chapter 268. Python program to multiply two matrices

for r in result:
    print(r)

Output:

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

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

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

# Python program to Print unique rows in a 


# given boolean matrix using Set with tuples
  
# Function to print unique rows in a given boolean matrix
  
def uniqueRows(input):
  
    # convert each row (list) into tuple
    # we are mapping tuple function on each row of 
    # input matrix
    input = map(tuple, input)
  
    # put all rows in set
    result = set(input)
  
    # print all unique rows
    for row in list(result):
        print (row)
  
# Driver program
if __name__ == "__main__":
    input = [[0, 1, 0, 0, 1],
             [1, 0, 1, 1, 0],
             [0, 1, 0, 0, 1],
             [1, 1, 1, 0, 0]]
    uniqueRows(input)

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

Queries in a Matrix - GeeksforGeeks


Given a matrix M of size m x n ( 1 <= m,n <= 1000 ). It is initially filled with integers
from 1 to m x n sequentially in a row major order. The task is to process a list of queries
manipulating M such that every query is one of the following three.

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

After first R(1, 2) matrix becomes,


{{4, 5, 6},
{1, 2, 3},
{7, 8, 9}}
After first C(1, 2) matrix becomes,
{{5, 4, 6},
{2, 1, 3},
{8, 7, 9}}

Input : m = 1234, n = 5678


R(1, 2)
P(1, 1)
P(2, 1)
C(1, 2)
P(1, 1)
P(2, 1)
Output: value at (1, 1) = 5679
value at (2, 1) = 1
value at (1, 1) = 5680
value at (2, 1) = 2

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.

Below is C++ implementation of above idea.

// C++ implementation of program


#include<bits/stdc++.h>
using namespace std;
  
// Fills initial values in rows[] and cols[]
void preprocessMatrix(int rows[], int cols[],
                     int m, int n)
{

1847
Chapter 270. Queries in a Matrix

    // Fill rows with 1 to m-1


    for (int i=0; i<m; i++)
        rows[i] = i;
  
    // Fill columns with 1 to n-1
    for (int i=0; i<n; i++)
        cols[i] = i;
}
  
// Function to perform queries on matrix
// m --> number of rows
// n --> number of columns
// ch --> type of query
// x --> number of row for query
// y --> number of column for query
void queryMatrix(int rows[], int cols[], int m,
                 int n, char ch, int x, int y)
{
    // perform queries
    int tmp;
    switch(ch)
    {
    case 'R':
  
        // swap row x with y
        swap(rows[x-1], rows[y-1]);
        break;
  
    case 'C':
  
        // swap coloumn x with y
        swap(cols[x-1], cols[y-1]);
        break;
  
    case 'P':
  
        // Print value at (x, y)
        printf("value at (%d, %d) = %d\n", x, y,
                   rows[x-1]*n + cols[y-1]+1);
        break;
    }
    return ;
}
  
// Driver program to run the case
int main()
{
    int m = 1234, n = 5678;

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:

value at (1, 1) = 5679


value at (2, 1) = 1
value at (1, 1) = 5680
value at (2, 1) = 2

Time complexity : O(q) , q = number of queries


Axillary space : O(m+n)

Source

https://www.geeksforgeeks.org/queries-in-a-matrix/

1849
Chapter 271

Queries on number of Binary


sub-matrices of Given size

Queries on number of Binary sub-matrices of Given size - GeeksforGeeks


Given a Binary Matrix of size N X M, the task is to answer Q queries of the following
type;

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

1111 1111 1111 1111


0111 0111 0111 0111

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:

1) If i = 0 OR j = 0 In this Case, dp[i][j] = 1, because only 1 X 1 is the only


square matrix that can be formed at 0th row or 0th column whose all elements
are equal
to m[i][j] and the last element is (i, 0) or (0, j).
2) If m[i][j] = m[i-1][j] = m[i][j-1] = m[i-1][j-1] dp[i][j] = min(dp[i][j-1],
dp[i-1][j], dp[i-1][j-1]) + 1, if the binary number at m[i][j] is equal to the binary
number at m[i-1][j], m[i-1][j-1] and m[i][j-1]. Because if the current binary number
is equal to all the three binary numbers it will form a 2 X 2 square sub-matrix
where all the elements are equal. Also, it will contribute 1 more row and column
to the square matrix with all equal element at position m[i-1][j], m[i-1][j-1] and
m[i][j-1].
dp[i][j] = 1, if above conditions do not meet because a single cell will always
contribute a 1 X 1 sub matrix.

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++

// CPP Program to answer queries on number of


// submatrix of given size
#include <bits/stdc++.h>
using namespace std;
  
#define MAX 100
#define N 5
#define M 4
  
// Return the minimum of three numbers
int min(int a, int b, int c)
{
    return min(a, min(b, c));
}
  
// Solve each query on matrix
void solveQuery(int n, int m, int mat[N][M], int q, 
                             int a[], int binary[])
{
    int dp[n][m], max = 1;
  
    // For each of the cell.
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
  
            // finding submatrix size of oth row 
            // and column.
            if (i == 0 || j == 0)
                dp[i][j] = 1;
  
            // intermediate cells.
            else if ((mat[i][j] == mat[i - 1][j]) &&
                     (mat[i][j] == mat[i][j - 1]) && 
                     (mat[i][j] == mat[i - 1][j - 1])) {
  
                dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1],
                               dp[i][j - 1])

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

// Java Program to answer queries on number of


// submatrix of given size
import java.io.*;
  
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.
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
      
                // finding submatrix size of oth row 
                // and column.
                if (i == 0 || j == 0)
                    dp[i][j] = 1;
      
                // intermediate cells.
                else if ((mat[i][j] == mat[i - 1][j]) 
                      && (mat[i][j] == mat[i][j - 1])

1854
Chapter 271. Queries on number of Binary sub-matrices of Given size

                 && (mat[i][j] == mat[i - 1][j - 1]))


                 {
      
                    dp[i][j] = min(dp[i - 1][j],
                               dp[i - 1][j - 1],
                                dp[i][j - 1]) + 1;
      
                    if (max < dp[i][j])
                        max = dp[i][j];
                }
      
                else
                    dp[i][j] = 1;
            }
        }
      
        int freq0[] = new int[MAX];
        int freq1[] = new int[MAX];
      
        // 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)
                System.out.println( freq0[a[i]]);
            else
                System.out.println( freq1[a[i]]);
        }
    }
      
    // Driver Program
  
    public static void main (String[] args) 

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

        for (int i = 0; i < n; i++) 


        {
            for (int j = 0; j < m; j++) 
            {
      
                // finding submatrix size 
                // of oth row and column.
                if (i == 0 || j == 0)
                    dp[i, j] = 1;
      
                // intermediate cells.
                else if ((mat[i, j] == mat[i - 1, j]) && 
                         (mat[i, j] == mat[i, j - 1]) && 
                         (mat[i, j] == mat[i - 1, j - 1]))
                { 
      
                    dp[i, j] = min(dp[i - 1, j],
                                   dp[i - 1, j - 1],
                                   dp[i, j - 1]) + 1;
      
                    if (max < dp[i, j])
                        max = dp[i, j];
                }
      
                else
                    dp[i, j] = 1;
            }
        }
      
        int []freq0 = new int[MAX];
        int []freq1 = new int[MAX];
      
        // 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--) 
        {

1857
Chapter 271. Queries on number of Binary sub-matrices of Given size

            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)
                Console.WriteLine(freq0[a[i]]);
            else
                Console.WriteLine(freq1[a[i]]);
        }
    }
      
    // Driver Code
    public static void Main () 
    {
        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.

Output:

4
1

Time Complexity of the above algorithm is O(n * m)


Improved By : vt_m

Source
https://www.geeksforgeeks.org/queries-number-binary-sub-matrices-given-size/

1858
Chapter 272

Rat in a Maze with multiple


steps or jump allowed

Rat in a Maze with multiple steps or jump allowed - GeeksforGeeks


This is the variation of Rat in Maze
A Maze is given as N*N binary matrix of blocks where source block is the upper left most
block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A
rat starts from source and has to reach destination. The rat can move only in two directions:
forward and down.
In the maze matrix, 0 means the block is dead end and non-zero number means the block
can be used in the path from source to destination. The non-zero value of mat[i][j] indicates
number of maximum jumps rat can make from cell mat[i][j].
In this variation, Rat is allowed to jump multiple steps at a time instead of 1.
Examples
Examples:

Input : { {2, 1, 0, 0},


{3, 0, 0, 1},
{0, 1, 0, 1},
{0, 0, 0, 1}
}
Output : { {1, 0, 0, 0},
{1, 0, 0, 1},
{0, 0, 0, 1},
{0, 0, 0, 1}
}

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

Let's try in horizontal direction -


M[0][1] won't lead to solution and M[0][2] is 0 which is dead end.
So, backtrack and try in down direction.
Rat jump down to M[1][0] which eventually leads to solution.

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.

while there are untried paths


{
generate the next path
if this path has all blocks as non-zero
{
print this path;
}
}

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.

Implementation of Backtracking solution


C/C++

/* C/C++ program to solve Rat in a Maze problem 


   using backtracking */
#include <stdio.h>
  

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

Rat in a Maze | Backtracking-2

Rat in a Maze | Backtracking-2 - GeeksforGeeks


We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in
a Mazeas another example problem that can be solved using Backtracking.
A Maze is given as N*N binary matrix of blocks where source block is the upper left most
block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A
rat starts from source and has to reach the destination. The rat can move only in two
directions: forward and down.
In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in
the path from source to destination. Note that this is a simple version of the typical Maze
problem. For example, a more complex version can be that the rat can move in 4 directions
and a more complex version can be with a limited number of moves.
Following is an example maze.

Gray blocks are dead ends (value = 0).

Following is binary matrix representation of the above maze.

{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 a maze with highlighted solution path.

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.

while there are untried paths


{
generate the next path
if this path has all blocks as 1
{
print this path;
}
}

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) 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 works then unmark this cell as 0
(BACKTRACK) and return false.

Implementation of Backtracking solution

C/C++

/* C/C++ program to solve Rat in a Maze problem using


   backtracking */
#include<stdio.h>
  
// 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] == 1)
        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},

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

/* Java program to solve Rat in a Maze problem using


   backtracking */
  
public class RatMaze
{
    final int N = 4;
  
    /* A utility function to print solution matrix
       sol[N][N] */
    void printSolution(int sol[][])
    {
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
                System.out.print(" " + sol[i][j] +
                                 " ");
            System.out.println();
        }
    }
  
    /* A utility function to check if x,y is valid
        index for N*N maze */
    boolean isSafe(int maze[][], int x, int y)
    {
        // if (x,y outside maze) return false
        return (x >= 0 && x < N && y >= 0 &&
                y < N && maze[x][y] == 1);
    }
  
    /* This function solves the Maze problem using
       Backtracking. It mainly uses solveMazeUtil()
       to solve the problem. It returns false if no

1868
Chapter 273. Rat in a Maze | Backtracking-2

       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.*/
    boolean solveMaze(int maze[][])
    {
        int sol[][] = {{0, 0, 0, 0},
            {0, 0, 0, 0},
            {0, 0, 0, 0},
            {0, 0, 0, 0}
        };
  
        if (solveMazeUtil(maze, 0, 0, sol) == false)
        {
            System.out.print("Solution doesn't exist");
            return false;
        }
  
        printSolution(sol);
        return true;
    }
  
    /* A recursive utility function to solve Maze
       problem */
    boolean solveMazeUtil(int maze[][], int x, int y,
                          int sol[][])
    {
        // 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))
                return true;
  
            /* If moving in x direction doesn't give
               solution then  Move down in y direction */
            if (solveMazeUtil(maze, x, y + 1, sol))
                return true;

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

# Python3 program to solve Rat in a Maze 


# problem using backracking 
  
# Maze size
N = 4
  
# A utility function to print solution matrix sol
def printSolution( sol ):
      
    for i in sol:
        for j in i:
            print(str(j) + " ", end="")
        print("")
  
# A utility function to check if x,y is valid
# index for N*N Maze
def isSafe( maze, x, y ):
      
    if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1:
        return True
      
    return False

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

    # Initialising the maze


    maze = [ [1, 0, 0, 0],
             [1, 1, 0, 1],
             [0, 1, 0, 0],
             [1, 1, 1, 1] ]
               
    solveMaze(maze)
  
# This code is contributed by Shiv Shankar

Output: The 1 values show the path for rat

1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1

Below is an extended version of this problem.Count number of ways to reach destination in


a Maze

Source

https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/

1872
Chapter 274

Remove all outgoing edges


except edge with minimum
weight

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 :

Input : Adjacency Matrix of input graph :


| 1 2 3 4
---------------
1 | 0 3 2 5
2 | 0 2 4 7
3 | 1 2 0 3
4 | 5 2 1 3

Output : Adjacency Matrix of output graph :


| 1 2 3 4
---------------
1 | 0 0 2 0
2 | 0 2 0 0
3 | 1 0 0 0
4 | 0 0 1 0

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

// CPP program for minimizing graph


#include <bits/stdc++.h>
  
using namespace std;
  
// Utility function for
// finding min of a row
int minFn(int arr[])
{
    int min = INT_MAX;
      
    for (int i = 0; i < 4; i++)
        if (min > arr[i])
            min = arr[i];
    return min;
}
  
// Utility function for minimizing graph
void minimizeGraph(int arr[][4])
{
    int min;
      
    // Set empty edges to INT_MAX
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            if (arr[i][j] == 0)
                arr[i][j] = INT_MAX;
  
    // Finding minimum of each row
    // and deleting rest of edges
    for (int i = 0; i < 4; i++) {
          
        // Find minimum element of row
        min = minFn(arr[i]);
          
        for (int j = 0; j < 4; 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] == INT_MAX))
                arr[i][j] = 0;
            else
                min = 0;
        }
    }
      
    // Print result;

1875
Chapter 274. Remove all outgoing edges except edge with minimum weight

    for (int i = 0; i < 4; i++) {


        for (int j = 0; j < 4; j++)
            cout << arr[i][j] << " ";
        cout << "\n";
    }
}
  
// Driver Program
int main()
{   
    // Input Graph
    int arr[4][4] = { 1, 2, 4, 0,
                    0, 0, 0, 5,
                    0, 2, 0, 3,
                    0, 0, 0, 0 };
      
    minimizeGraph(arr);
      
    return 0;
}

Java

// Java program for 


// minimizing graph
import java.io.*;
import java.util.*;
import java.lang.*;
  
class GFG
{
      
// Utility function for
// finding min of a row
static int minFn(int arr[])
{
    int min = Integer.MAX_VALUE;
      
    for (int i = 0; 
             i < arr.length; i++)
        if (min > arr[i])
            min = arr[i];
    return min;
}
  
// Utility function 
// for minimizing graph
static void minimizeGraph(int arr[][])

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

Time Complexity: O(n^2)

Source

https://www.geeksforgeeks.org/minimum-weighted-graph/

1878
Chapter 275

Removing row or column wise


duplicates from matrix of
characters

Removing row or column wise duplicates from matrix of characters - GeeksforGeeks


Given a matrix of characters containing only lowercase letters, form a new string from the
matrix that remain after removing the duplicate characters from each row and column. The
remaining characters are joined row-wise to form the string.
Examples:

Input : Matrix of characters (Or array


of strings)
aabcd
effgh
iijkk
lmnoo
pqqrs
ttuvw
xxyyz
Output : bcdeghjlmnprsuvwz
The characters that appear more than once
in their row or column are removed.

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++

// CPP code to form string after removing


// duplicates from rows and columns.
#include <bits/stdc++.h>
using namespace std;
  
// Function to check duplicates
// in row and column
void findDuplciates(string a[], int n, int m)
{
    // Create an array isPresent and initialize
    // all entries of it as false. The value of
    // isPresent[i][j] is going to be true if
    // s[i][j] is present in its row or column.
    bool isPresent[n][m];
    memset(isPresent, 0, sizeof(isPresent));
  
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
  
            // Checking every row for
            // duplicates of a[i][j]
            for (int k = 0; k < n; k++) {
                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

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#

// C# code to form string 


// after removing duplicates
// from rows and columns.
using System;
  
class GFG
{
    // Function to check 
    // duplicates in row 
    // and column
    static void findDuplciates(string []a, 
                               int n, int m)
    {
        // Create an array isPresent 
        // and initialize all entries 
        // of it as false. The value 
        // of isPresent[i,j] is going 
        // to be true if s[i,j] is 
        // present in its row or column.
        bool [,]isPresent = new bool[n, m];
          
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++) 
            {
      
                // Checking every row for
                // duplicates of a[i,j]
                for (int k = 0; k < n; k++) 

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

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 :

Input : mat[3][4] = {1, 2, 3, 3,


4, 5, 6, 6
7, 8, 9, 9}
Output : 1 1 3 3
1 1 3 3
1 1 3 3
For index (0,2), GCD of row 0 is 1, GCD of row 2 is 3.
So replace index (0,2) with 3 (3>1).

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

Below is the implementation of this approach:

C++

// C++ program to replace each each element with


// maximum of GCD of row or column.
#include<bits/stdc++.h>
using namespace std;
#define R 3
#define C 4
  
// returning the greatest common divisor of two number
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a%b);
}
  
// Finding GCD of each row and column and replacing
// with each element with maximum of GCD of row or
// column.
void replacematrix(int mat[R][C], int n, int m)
{
    int rgcd[R] = { 0 }, cgcd[C] = { 0 };
  
    // Calculating GCD of each row and each column in 
    // O(mn) and store in arrays.
    for (int i = 0; i < n; i++)
    {
        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] = max(rgcd[i], cgcd[j]);
}
  
// Driven Program
int main()
{
    int m[R][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

// Java program to replace each each element with


// maximum of GCD of row or column.
import java .io.*;
  
class GFG
{
      static int R = 3;
      static int C = 4;
  
      // returning the greatest common 
      // divisor of two number
      static int gcd(int a, int b)
      {
         if (b == 0)
         return a;
         return gcd(b, a%b);
      }
  
// Finding GCD of each row and column and 
// replacing with each element with maximum
// of GCD of row or column.
static void replacematrix(int [][]mat, int n, int m)
{
    int []rgcd = new int[R] ;
    int []cgcd = new int[C];
  
    // Calculating GCD of each row and each column in 
    // O(mn) and store in arrays.
    for (int i = 0; i < n; i++)

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#

// C# program to replace each each element with


// maximum of GCD of row or column.
using System;
  
class GFG
{
      static int R = 3;
      static int C = 4;
    
      // returning the greatest common 

1887
Chapter 276. Replace every matrix element with maximum of GCD of row or column

      // divisor of two number


      static int gcd(int a, int b)
      {
        if (b == 0)
        return a;
        return gcd(b, a%b);
      }
  
// Finding GCD of each row and column and
// replacing with each element with maximum
// of GCD of row or column.
static void replacematrix(int [,]mat, int n, int m)
{
    int []rgcd = new int[R] ;
    int []cgcd = new int[C];
  
    // Calculating GCD of each row and each column in 
    // O(mn) and store in arrays.
    for (int i = 0; i < n; i++)
    {
        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 (){
    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++)
        Console.Write(m[i,j] + " ");

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

Time Complexity : O(mn).


Axillary Space : O(m + n).
Improved By : vt_m

Source

https://www.geeksforgeeks.org/replace-matrix-element-maximum-gcd-row-column/

1889
Chapter 277

Return previous element in an


expanding matrix

Return previous element in an expanding matrix - GeeksforGeeks


We have a square matrix whose size is continuously expanding by factor of 2. Given a
sequence present in the matrix at position (i, j) at any point of time, we need to return
sequence present at position (i, (j + N -1)%N) where N is size of the matrix.
When we say the matrix is expanding, the expanded matrix is formed by multiplying each
element of the original 2 x 2 matrix with current N x N matrix itself. The expanded matrix
will have dimensions 2N x 2N.

For Instance, consider below 2x2 matrix,


[a b]
[c d]

Expanding it will result in a 4x4 matrix as follows:


ax[a b] bx[a b] [aa ab ba bb]
[c d] [c d] [ac ad bc bd]
--> [ca cb da db]
cx[a b] dx[a b] [cc cd dc dd]
[c d] [c d]

Expanding it again results in an 8x8 matrix as follows, and so on.

ax[aa ab ba bb] bx[aa ab ba bb]


[aaa aab aba abb baa bab bba bbb]
[ac ad bc bd] [ac ad bc bd]
[aac aad abc abd bac bad bbc bbd]
[ca cb da db] [ca cb da db]
[aca acb ada adb bca bcb bda bdb]
[cc cd dc dd] [cc cd dc dd]
[acc acd adc add bcc bcd bdc bdd]
--> [caa cab cba cbb daa dab dba dbb]
cx[aa ab ba bb] dx[aa ab ba bb] [cac cad cbc cbd dac dad dbc dbd]

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:

Input: str = dda


Output: dcb

Input: str = cca


Output: ddb

Input: str = aacbddc


Output: aacbdcd

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++

// Program to return previous element in an expanding


// matrix.
#include <bits/stdc++.h>
using namespace std;
  
// Returns left of str in an expanding matrix of
// a, b, c  and d.
string findLeft(string str)
{
    int n = str.length();
  
    // Start from rightmost position
    while (n--)
    {

1891
Chapter 277. Return previous element in an expanding matrix

        // If the current character is ‘b’ or ‘d’,


        // change to ‘a’ or ‘c’ respectively and
        // break the loop
        if (str[n] == 'd')
        {
            str[n] = 'c';
            break;
        }
        if (str[n] == 'b')
        {
            str[n] = 'a';
            break;
        }
  
        // If the current character is ‘a’ or ‘c’,
        // change it to ‘b’ or ‘d’ respectively
        if (str[n] == 'a')
            str[n] = 'b';
        else if (str[n] == 'c')
            str[n] = 'd';
    }
  
    return str;
}
  
// driver program to test above method
int main()
{
    string str = "aacbddc";
    cout << "Left of " << str << " is "
         << findLeft(str);
   return 0;
}

Java

// Java program to return previous element


// in an expanding matrix
import java.io.*;
   
class GFG 
{
    // Returns left of str in an expanding matrix 
    // of a, b, c  and d.
    static StringBuilder findLeft(StringBuilder str)
    {
        int n = str.length();
       

1892
Chapter 277. Return previous element in an expanding matrix

        // Start from rightmost position


        while (n > 0)
        {
            n--;
            
            // If the current character is b or d,
            // change to a or c respectively and
            // break the loop
            if (str.charAt(n) == 'd')
            {
                str.setCharAt(n,'c');
                break;
            }
            if (str.charAt(n) == 'b')
            {
                str.setCharAt(n,'a');
                break;
            }
       
            // If the current character is a or c,
            // change it to b or d respectively
            if (str.charAt(n) == 'a')
                str.setCharAt(n,'b');
            else if (str.charAt(n) == 'c')
                str.setCharAt(n,'d');
        }
       
        return str;
    }
       
    // driver program to test above method
    public static void main (String[] args) 
    {
        StringBuilder str = new StringBuilder("aacbddc");
        System.out.print("Left of " + str + " is " + 
                                    findLeft(str));
    }
}
   
// This code is contributed by Prakriti Gupta

Output :

Left of aacbddc is aacbdcd

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

Reverse Diagonal elements of


matrix

Reverse Diagonal elements of matrix - GeeksforGeeks


Given a square matrix of order n*n, we have to reverse the elements of both diagonals.
Examples:

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}

Output :{16, 2, 3, 13,


5, 11, 10, 8,
9, 7, 6, 12,
4, 14, 15, 1}

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

// Java Program to Reverse 


// Diagonal elements of matrix
import java.io.*;
  

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

        for (j = 0; j < N; ++j)


            Console.Write(array[i, j] + " ");
            Console.WriteLine();
    }
}
  
// Driver Code
public static void Main ()
{
    int [,]matrix = {{1, 2, 3, 4},
                     {5, 6, 7, 8},
                     {9, 10, 11, 12},
                     {13, 14, 15, 16}};
    reverseDiagonal(matrix);
}
}
  
// This code is contributed 
// by anuj_67.

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

Rotate Matrix Elements

Rotate Matrix Elements - GeeksforGeeks


Given a matrix, clockwise rotate elements in it.
Examples:

Input
1 2 3
4 5 6
7 8 9

Output:
4 1 2
7 5 3
8 9 6

For 4*4 matrix


Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

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++

// C++ program to rotate a matrix


  
#include <bits/stdc++.h>
#define R 4
#define C 4
using namespace std;
  
// A function to rotate a matrix mat[][] of size R x C.
// Initially, m = R and n = C
void rotatematrix(int m, int n, int mat[R][C])
{
    int row = 0, col = 0;
    int prev, curr;
  
    /*
       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 (int i = col; i < n; i++)
        {
            curr = mat[row][i];

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

/* Driver program to test above functions */


int main()
{
    // Test Case 1
    int a[R][C] = { {1,  2,  3,  4},
        {5,  6,  7,  8},
        {9,  10, 11, 12},
        {13, 14, 15, 16}  };
  
    // Tese Case 2
    /* int a[R][C] = {{1, 2, 3},
                      {4, 5, 6},
                      {7, 8, 9}
                     };
     */  rotatematrix(R, C, a);
    return 0;
}

Java

// Java program to rotate a matrix


import java.lang.*;
import java.util.*;
  
class GFG
{
    static int R = 4;
    static int C = 4;
  
    // A function to rotate a matrix 
    // mat[][] of size R x C.
    // Initially, m = R and n = C
    static void rotatematrix(int m,
                    int n, int mat[][])
    {
        int row = 0, col = 0;
        int prev, curr;
  
        /*
        row - Staring row index
        m - ending row index
        col - starting column index
        n - ending column index
        i - iterator
        */
        while (row < m && col < n)
        {
      

1903
Chapter 279. Rotate Matrix Elements

            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 (int i = col; i < n; i++)
            {
                curr = mat[row][i];
                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];

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

# Python program to rotate a matrix


  
# Function to rotate a matrix
def rotateMatrix(mat):
  
    if not len(mat):
        return
      
    """

1905
Chapter 279. Rotate Matrix Elements

        top : starting row index


        bottom : ending row index
        left : starting column index
        right : ending column index
    """
  
    top = 0
    bottom = len(mat)-1
  
    left = 0
    right = len(mat[0])-1
  
    while left < right and top < bottom:
  
        # Store the first element of next row,
        # this element will replace first element of
        # current row
        prev = mat[top+1][left]
  
        # Move elements of top row one step right
        for i in range(left, right+1):
            curr = mat[top][i]
            mat[top][i] = prev
            prev = curr
  
        top += 1
  
        # Move elements of rightmost column one step downwards
        for i in range(top, bottom+1):
            curr = mat[i][right]
            mat[i][right] = prev
            prev = curr
  
        right -= 1
  
        # Move elements of bottom row one step left
        for i in range(right, left-1, -1):
            curr = mat[bottom][i]
            mat[bottom][i] = prev
            prev = curr
  
        bottom -= 1
  
        # Move elements of leftmost column one step upwards
        for i in range(bottom, top-1, -1):
            curr = mat[i][left]
            mat[i][left] = prev
            prev = curr

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#

// C# program to rotate a matrix


using System;
  
class GFG {
      
    static int R = 4;
    static int C = 4;
  
    // A function to rotate a matrix 
    // mat[][] of size R x C.
    // Initially, m = R and n = C
    static void rotatematrix(int m,
                        int n, int [,]mat)
    {
        int row = 0, col = 0;

1907
Chapter 279. Rotate Matrix Elements

        int prev, curr;


  
        /*
        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 (int i = col; i < n; i++)
            {
                curr = mat[row,i];
                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;

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

        /* Move elements of last column


           from the remaining columns */
        for ($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 ($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 ($i = $m - 1; 
                 $i >= $row; $i--)
            {
                $curr = $mat[$i][$col];
                $mat[$i][$col] = $prev;
                $prev = $curr;
            }
        }
        $col++;
    }
  
    // Print rotated matrix
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        echo $mat[$i][$j] . " ";
        echo "\n";
    }
}
  

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

Improved By : nitin mittal, ChitraNayal

Source

https://www.geeksforgeeks.org/rotate-matrix-elements/

1912
Chapter 280

Rotate a Matrix by 180 degree

Rotate a Matrix by 180 degree - GeeksforGeeks


Given a square matrix the task is that we turn it by 180 degrees in anti-clockwise direction
without using any extra space.
Examples :

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

Method : 1 (Only prints rotated matrix)


The solution of this problem is that to rotate a matrix by 180 degree we can easily follow
that step

Matrix = a00 a01 a02


a10 a11 a12
a20 a21 a22

1913
Chapter 280. Rotate a Matrix by 180 degree

when we rotate it by 90 degree


then matrix is
Matrix = a02 a12 a22
a01 a11 a21
a00 a10 a20

when we rotate it by again 90


degree then matrix is
Matrix = a22 a21 a20
a12 a11 a10
a02 a01 a00

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++

// C++ program to rotate a matrix by 180 degrees


#include <bits/stdc++.h>
#define N 3
using namespace std;
  
// Function to Rotate the matrix by 180 degree
void rotateMatrix(int mat[][N])
{
    // Simply print from last cell to first cell.
    for (int i = N - 1; i >= 0; i--) {
        for (int j = N - 1; j >= 0; j--)
            printf("%d ", mat[i][j]);
  
        printf("\n");
    }
}
  
// Driven code
int main()
{
    int mat[N][N] = {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };
  
    rotateMatrix(mat);
    return 0;
}

Java

1914
Chapter 280. Rotate a Matrix by 180 degree

// Java program to rotate a


// matrix by 180 degrees
import java.util.*;
  
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--)
                System.out.print(mat[i][j] + " ");
  
            System.out.println();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        int[][] mat = { { 1, 2, 3 },
                        { 4, 5, 6 },
                        { 7, 8, 9 } };
  
        rotateMatrix(mat);
    }
}
  
// This code is contributed by ChitraNayal

Python3

# Python3 program to 


# rotate a matrix by 
# 180 degrees
N = 3;
  
# Function to Rotate 
# the matrix by 180 degree
def rotateMatrix(mat):
      
    # Simply print from
    # last cell to first cell.

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

Time complexity : O(N*N)


Auxiliary Space : O(1)

Method : 2(In-place rotation)


There are four steps :
1- Find transpose of matrix.
2- Reverse columns of the transpose.
3- Find transpose of matrix.
4- Reverse columns of the transpose

Let the given matrix be


1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

First we find transpose.


1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

Then we reverse elements of every column.


4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

then transpose again


4 3 2 1
8 7 6 5
12 11 10 9
16 15 14 13

Then we reverse elements of every column again


16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1

C++

// C++ program for left rotation of matrix by 180


#include <bits/stdc++.h>
using namespace std;

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

// Java program for left


// rotation of matrix by 180
import java.util.*;
  
class GFG {
    static int R = 4, C = 4, t = 0;
  
    // Function to rotate the
    // matrix by 180 degree
    static void reverseColumns(int arr[][])
    {
        for (int i = 0; i < C; i++) {
            for (int 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
    static void transpose(int arr[][])
    {
        for (int i = 0; i < R; i++) {
            for (int j = i; j < C; j++) {
                t = arr[i][j];
                arr[i][j] = arr[j][i];
                arr[j][i] = t;
            }
        }
    }
  
    // Function for display the matrix
    static void printMatrix(int arr[][])
    {
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
  

1920
Chapter 280. Rotate a Matrix by 180 degree

    // Function to anticlockwise


    // rotate matrix by 180 degree
    static void rotate180(int arr[][])
    {
        transpose(arr);
        reverseColumns(arr);
        transpose(arr);
        reverseColumns(arr);
    }
  
    // 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 } };
  
        rotate180(arr);
        printMatrix(arr);
    }
}
  
// This code is contributed by ChitraNayal

C#

// C# program for left


// rotation of matrix by 180
using System;
  
class GFG {
    static int R = 4, C = 4, t = 0;
  
    // Function to rotate the
    // matrix by 180 degree
    static void reverseColumns(int[, ] arr)
    {
        for (int i = 0; i < C; i++) {
            for (int j = 0, k = C - 1;
                 j < k; j++, k--) {
                t = arr[j, i];
                arr[j, i] = arr[k, i];
                arr[k, i] = t;
            }
        }
    }
  

1921
Chapter 280. Rotate a Matrix by 180 degree

    // Function for transpose of matrix


    static void transpose(int[, ] arr)
    {
        for (int i = 0; i < R; i++) {
            for (int j = i; j < C; j++) {
                t = arr[i, j];
                arr[i, j] = arr[j, i];
                arr[j, i] = t;
            }
        }
    }
  
    // Function for display the matrix
    static void printMatrix(int[, ] arr)
    {
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++)
                Console.Write(arr[i, j] + " ");
            Console.WriteLine();
        }
    }
  
    // Function to anticlockwise
    // rotate matrix by 180 degree
    static void rotate180(int[, ] arr)
    {
        transpose(arr);
        reverseColumns(arr);
        transpose(arr);
        reverseColumns(arr);
    }
  
    // Driver Code
    static public void Main()
    {
        int[, ] arr = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
  
        rotate180(arr);
        printMatrix(arr);
    }
}
  
// This code is contributed by ajit

Python 3

1922
Chapter 280. Rotate a Matrix by 180 degree

# Python 3 program for left rotation of matrix by 180


   
R = 4
C = 4
   
# Function to rotate the matrix by 180 degree
def reverseColumns(arr):
    for i in range(C):
        j = 0
        k = C-1
        while j < k:
            t = arr[j][i]
            arr[j][i] = arr[k][i]
            arr[k][i] = t
            j += 1
            k -= 1
              
# Function for transpose of matrix
def transpose(arr):
    for i in range(R):
        for j in range(i, C):
            t = arr[i][j]
            arr[i][j] = arr[j][i]
            arr[j][i] = t
   
# Function for display the matrix
def printMatrix(arr):
    for i in range(R):
        for j in range(C):
            print(arr[i][j], end = " ");
        print();
   
# Function to anticlockwise rotate matrix
# by 180 degree
def rotate180(arr):
    transpose(arr);
    reverseColumns(arr);
    transpose(arr);
    reverseColumns(arr);
   
# Driven code
arr = [ [ 1, 2, 3, 4 ],
        [ 5, 6, 7, 8 ],
        [9, 10, 11, 12 ],
        [13, 14, 15, 16 ] ];
rotate180(arr);
printMatrix(arr);

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

Time complexity : O(R*C)


Auxiliary Space : O(1)
Improved By : ChitraNayal, jit_t, Mithun Kumar

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

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

An N x N matrix will have floor(N/2) square cycles.


For example, a 3 X 3 matrix will have 1 cycle. The cycle is formed by its 1st row, last
column, last row, and 1st column.
For each square cycle, we swap the elements involved with the corresponding cell in the
matrix in the clockwise direction. We just need a temporary variable for this.
Explanation:

Let size of row and column be 3.


During first iteration –
a[i][j] = Element at first index (leftmost corner top)= 1.
a[j][n-1-i]= Rightmost corner top Element = 3.
a[n-1-i][n-1-j] = Righmost corner bottom element = 9.
a[n-1-j][i] = Leftmost corner bottom element = 7.
Move these elements in the clockwise direction.

During second iteration –


a[i][j] = 2.
a[j][n-1-j] = 6.
a[n-1-i][n-1-j] = 8.
a[n-1-j][i] = 4.
Similarly, move these elements in the clockwise direction.

Below is the implementation of above approach:

C++

// C++ implementation of above approach


#include <bits/stdc++.h>
using namespace std;
  
#define N 4
  
// Function to rotate the matrix 90 degree clockwise
void rotate90Clockwise(int a[N][N])
{
  
    // 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];

1927
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space

            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
void printMatrix(int arr[N][N])
{
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            cout << arr[i][j] << " ";
        cout << '\n';
    }
}
  
// Driver code
int main()
{
    int arr[N][N] = { { 1, 2, 3, 4 },
                      { 5, 6, 7, 8 },
                      { 9, 10, 11, 12 },
                      { 13, 14, 15, 16 } };
    rotate90Clockwise(arr);
    printMatrix(arr);
    return 0;
}

Java

// Java implementation of above approach


import java.io.*;
  
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++)
        {

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

# Function to rotate the matrix


# 90 degree clockwise
def rotate90Clockwise(A):
    N = len(A[0])
    for i in range(N // 2):
        for j in range(i, N - i - 1):
            temp = A[i][j]
            A[i][j] = A[N - 1 - j][i]

1929
Chapter 281. Rotate a matrix by 90 degree in clockwise direction without using any extra
space

            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 to print the matrix
def printMatrix(A):
    N = len(A[0])
    for i in range(N):
        print(A[i])
  
# Driver code
A = [[1, 2, 3, 4],
     [5, 6, 7, 8], 
     [9, 10, 11, 12], 
     [13, 14, 15, 16]]
rotate90Clockwise(A)
printMatrix(A)
  
# This code was contributed 
# by pk_tautolo

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

Improved By : inderDuMCA, pk_tautolo, ChitraNayal

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

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

An approach that requires extra space is already discussed in below set:


Inplace rotate square matrix by 90 degrees | Set 1
In this post another approach is discussed which is much simpler than the above approach.
There are two steps :

1. Find transpose of matrix.


2. Reverse columns of the transpose.

Illustration of above steps :

Let the given matrix be


1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

First we find transpose.


1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

Then we reverse elements of every column.


4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Below is the implementation of above steps.

C++

// C++ program for left rotation of matrix by 90


// degree without using extra space
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
  
// After transpose we swap elements of column
// one by one for finding left rotation of matrix
// by 90 degree
void reverseColumns(int arr[R][C])
{

1933
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2

    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 do 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 print 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 90 degree
void rotate90(int arr[R][C])
{
    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 } };
    rotate90(arr);
    printMatrix(arr);
    return 0;
}

Java

// JAVA Code for left Rotation of a


// matrix by 90 degree without using
// any extra space

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

    public static void main(String[] args)


    {
        int arr[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
  
        rotate90(arr);
        printMatrix(arr);
    }
}
  
// This code is contributed by Arnav Kr. Mandal.

C#

// C# program for left rotation


// of matrix by 90 degree
// without using extra space
using System;
  
class GFG {
    static int R = 4;
    static int C = 4;
  
    // 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 < C; i++)
            for (int j = 0, k = C - 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 < R; i++)
            for (int j = i; j < C; j++) {
                int temp = arr[j, i];

1936
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2

                arr[j, i] = arr[i, j];


                arr[i, j] = temp;
            }
    }
  
    // Function for print matrix
    static void printMatrix(int[, ] arr)
    {
  
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++)
                Console.Write(arr[i, j] + " ");
            Console.WriteLine("");
        }
    }
  
    // Function to anticlockwise
    // rotate matrix by 90 degree
    static void rotate90(int[, ] arr)
    {
        transpose(arr);
        reverseColumns(arr);
    }
  
    // Driver code
    static void Main()
    {
        int[, ] arr = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 },
                        { 13, 14, 15, 16 } };
  
        rotate90(arr);
        printMatrix(arr);
    }
  
    // This code is contributed
    // by Sam007
}

Python 3

# Python 3 program for left rotation of matrix by 90


# degree without using extra space
  
R = 4
C = 4
   

1937
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2

# After transpose we swap elements of column


# one by one for finding left rotation of matrix
# by 90 degree
def reverseColumns(arr):
    for i in range(C):
        j = 0
        k = C-1
        while j < k:
            t = arr[j][i]
            arr[j][i] = arr[k][i]
            arr[k][i] = t
            j += 1
            k -= 1
    
# Function for do transpose of matrix
def transpose(arr):
    for i in range(R):
        for j in range(i, C):
            t = arr[i][j]
            arr[i][j] = arr[j][i]
            arr[j][i] = t
   
# Function for print matrix
def printMatrix(arr):
    for i in range(R):
        for j in range(C):
            print(str(arr[i][j]), end =" ")
        print()
   
# Function to anticlockwise rotate matrix
# by 90 degree
def rotate90(arr):
    transpose(arr)
    reverseColumns(arr)
   
# Driven code
arr = [[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ];
rotate90(arr)
printMatrix(arr)

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

Time complexity :O(R*C)


Space complexity :O(1)
The above steps/program do left (or anticlockwise) rotation, how to right (or
clockwise) rotate?
To right rotate, we do following steps.

1. Find transpose of matrix.


2. Reverse rows of the transpose.

Illustration of above steps :

Let the given matrix be


1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

First we find transpose.


1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16

1940
Chapter 282. Rotate a matrix by 90 degree without using any extra space | Set 2

Then we reverse elements of every row.


13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

Improved By : Sam007, ChitraNayal

Source

https://www.geeksforgeeks.org/rotate-matrix-90-degree-without-using-extra-space-set-2/

1941
Chapter 283

Rotate each ring of matrix


anticlockwise by K elements

Rotate each ring of matrix anticlockwise by K elements - GeeksforGeeks


Given a matrix of order M*N and a value K, the task is to rotate each ring of the matrix
anticlockwise by K elements. If in any ring elements are less than and equal K then don’t
rotate it.
Examples:

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 :

• Make an auxiliary array temp[] of size M*N.

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.

Below is C++ implementation of above steps.

// C++ program to rotate individual rings by k in


// spiral order traversal.
#include<bits/stdc++.h>
#define MAX 100
using namespace std;
  
// Fills temp array into mat[][] using spiral order
// traveral.
void fillSpiral(int mat[][MAX], int m, int n, int temp[])
{
    int i, k = 0, l = 0;
  
    /*  k - starting row index
        m - ending row index
        l - starting column index
        n - ending column index  */
    int tIdx  = 0;  // Index in temp array
    while (k < m && l < n)
    {
        /* first row from the remaining rows */
        for (int i = l; i < n; ++i)
            mat[k][i] = temp[tIdx++];
        k++;
  
        /* last column from the remaining columns */
        for (int i = k; i < m; ++i)
            mat[i][n-1] = temp[tIdx++];
        n--;
  
        /* last row from the remaining rows */
        if (k < m)
        {
            for (int i = n-1; i >= l; --i)
                mat[m-1][i] = temp[tIdx++];
            m--;
        }
  
        /* first column from the remaining columns */
        if (l < n)

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

Rotate the matrix right by K


times

Rotate the matrix right by K times - GeeksforGeeks


Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the
right side.
Examples:

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

Lets take an example:

C++

// CPP program to rotate a matrix right by k times


#include <iostream>
  
// size of matrix
#define M 3
#define N 3
  
using namespace std;
  
// function to rotate matrix by k times
void rotateMatrix(int matrix[][M], int k) {
  // temporary array of size M
  int temp[M];
  
  // within the size of matrix
  k = k % M;
  
  for (int i = 0; i < N; i++) {
  
    // 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];
  }

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

// Java program to rotate a matrix 


// right by k times
  
class GFG
{
    // size of matrix
    static final int M=3;
    static final int N=3;
      
    // function to rotate matrix by k times
    static void rotateMatrix(int matrix[][], int k)
    {
        // temporary array of size M
        int temp[]=new int[M];
          
        // within the size of matrix
        k = k % M;
          
        for (int i = 0; i < N; i++)

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

# Python program to rotate 


# a matrix right by k times
  
# size of matrix
M = 3
N = 3
matrix = [[12, 23, 34],
          [45, 56, 67], 
          [78, 89, 91]]
  
# function to rotate
# matrix by k times
def rotateMatrix(k) :
  
    global M, N, matrix
      
    # temporary array 
    # of size M
    temp = [0] * M
      
    # within the size
    # of matrix
    k = k % M
      
    for i in range(0, N) : 
      
        # copy first M-k elements
        # to temporary array
        for t in range(0, M - k) :
            temp[t] = matrix[i][t]
      
        # copy the elements from 
        # k to end to starting
        for j in range(M - k, M) :
            matrix[i][j - M + k] = matrix[i][j]
      
        # copy elements from 
        # temporary array to end
        for j in range(k, M) :
            matrix[i][j] = temp[j - k]
      
# function to display
# the matrix
def displayMatrix() :
  
    global M, N, matrix

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#

// C# program to rotate a  


// matrix right by k times
using System;
  
class GFG {
      
    // size of matrix
    static int M=3;
    static int N=3;
      
    // function to rotate matrix by k times
    static void rotateMatrix(int [,] matrix, 
                             int k)
    {
          
        // temporary array of size M
        int [] temp=new int[M];
          
        // within the size of matrix
        k = k % M;
          
        for (int i = 0; i < N; i++)
        {
          
            // copy first M-k elements 
            // to temporary array
            for (int t = 0; t < M - k; t++)

1952
Chapter 284. Rotate the matrix right by K times

            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++)
            Console.Write(matrix[i, j] + " ");
            Console.WriteLine();
        }
    } 
      
    // Driver code
    public static void Main ()
    {
        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 KRV.

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

Improved By : KRV, manishshaw1

Source

https://www.geeksforgeeks.org/rotate-matrix-right-k-times/

1955
Chapter 285

Row wise sorting in 2D array

Row wise sorting in 2D array - GeeksforGeeks


Given a 2D array, sort each row of this array and print the result.
Examples:

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

Method 1 (Using Bubble Sort)


Start iterating through each row of given 2D array, and sort elements of each row using
efficient sorting algorithm.

1956
Chapter 285. Row wise sorting in 2D array

Java

// Java code to sort 2D matrix row-wise


import java.io.*;
  
public class Sort2DMatrix {
  
    static int sortRowWise(int m[][])
    {
        // loop for rows of matrix
        for (int i = 0; i < m.length; i++) {
  
            // loop for column of matrix
            for (int j = 0; j < m[i].length; j++) {
  
                // loop for comparison and swapping
                for (int k = 0; k < m[i].length - j; k++) {
                    if (m[i][k] > m[i][k + 1]) {
  
                        // swapping of elements
                        int t = m[i][k];
                        m[i][k] = m[i][k + 1];
                        m[i][k + 1] = t;
                    }
                }
            }
        }
  
        // printing the sorted matrix
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++)
                System.out.print(m[i][j] + " ");
            System.out.println();
        }
  
        return 0;
    }
  
    // driver code
    public static void main(String args[])
    {
        int m[][] = { { 9, 8, 7, 1 },
                      { 7, 3, 0, 2 },
                      { 9, 5, 3, 2 },
                      { 6, 3, 1, 2 } };
        sortRowWise(m);
    }
}

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

Method 2 (Using Library Function)


The idea is to use Arrays.sort() for every row of matrix.
Java

// Java code to sort 2D matrix row-wise


import java.io.*;
import java.util.Arrays;
  
public class Sort2DMatrix {
  
    static int sortRowWise(int m[][])
    {
        // One by one sort individual rows.
        for (int i = 0; i < m.length; i++)
            Arrays.sort(m[i]);
  
        // printing the sorted matrix
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++)
                System.out.print(m[i][j] + " ");
            System.out.println();
        }
  
        return 0;
    }
  
    // driver code
    public static void main(String args[])
    {
        int m[][] = { { 9, 8, 7, 1 },
                      { 7, 3, 0, 2 },
                      { 9, 5, 3, 2 },
                      { 6, 3, 1, 2 } };
  
        sortRowWise(m);
    }
}

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

Row-wise common elements in


two diagonals of a square matrix

Row-wise common elements in two diagonals of a square matrix - GeeksforGeeks


Given a square matrix, find out count of numbers that are same in same row and same in
both primary and secondary diagonals.
Examples :

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

// CPP program to find common elements in


// two diagonals.
#include <iostream>
#define MAX 100
using namespace std;
  
// Returns count of row wise same
// elements in two diagonals of
// mat[n][n]
int countCommon(int mat[][MAX], 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
int main()
{
    int mat[][MAX] = {{1, 2, 3}, 
                      {4, 5, 6},
                      {7, 8, 9}};
    cout << countCommon(mat, 3);
    return 0;
}

Java

// Java program to find common 


// elements in two diagonals.
import java.io.*;
  
class GFG
{
    int MAX = 100;
      
    // 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;
    }

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

# Python3 program to find common 


# elements in two diagonals.
  
Max = 100
  
# Returns count of row wise same
# elements in two diagonals of
# mat[n][n]
def countCommon(mat, n):
    res = 0
      
    for i in range(n):
          
        if mat[i][i] == mat[i][n-i-1] :
            res = res + 1
    return res     
  
# Driver Code
mat = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]
  
print(countCommon(mat, 3))
  
# This code is contributed by Anant Agarwal.

C#

// C# program to find common 


// elements in two diagonals.
using System;
  

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 :

Improved By : vt_m, jit_t

Source

https://www.geeksforgeeks.org/row-wise-common-elements-two-diagonals-square-matrix/

1964
Chapter 287

Row-wise vs column-wise
traversal of matrix

Row-wise vs column-wise traversal of matrix - GeeksforGeeks


Two common ways of traversing a matrix are row-major-order and column-major-order.
Row Major Order : When matrix is accessed row by row.
Column Major Order : When matrix is accessed column by column.
Examples:

Input : mat[][] = {{1, 2, 3},


{4, 5, 6},
{7, 8, 9}}
Output : Row-wise: 1 2 3 4 5 6 7 8 9
Col-wise : 1 4 7 2 5 8 3 6 9

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.

// C program showing time difference


// in row major and column major access
#include <stdio.h>
#include <time.h>
  
// taking MAX 10000 so that time difference
// can be shown
#define MAX 10000

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

Row major access time :0.492000 s


Column major access time :1.621000 s

Source

https://www.geeksforgeeks.org/row-wise-vs-column-wise-traversal-matrix/

1967
Chapter 288

Saddle point in a matrix

Saddle point in a matrix - GeeksforGeeks


Given a matrix of n x n size, the task is to find saddle point of the matrix. A saddle point
is an element of the matrix such that it is the minimum element in its row and maximum
in its column.
Examples :

Input: Mat[3][3] = { {1, 2, 3},


{4, 5, 6},
{7, 8, 9}}
Output: 7
7 is minimum in its row and maximum in its column.

Input: Mat[3][3] = {{1, 2, 3},


{4, 5, 6},
{10, 18, 4}}
Output: No saddle point

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

Below is implementation of above steps.

C++

// C++ program to illustrate Saddle point


#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to find saddle point
bool findSaddlePoint(int mat[MAX][MAX], int n)
{
    // Process all rows one by one
    for (int i = 0; i < n; i++)
    {
        // Find the minimum element of row i.
        // Also find column index of the minimum element
        int min_row = mat[i][0], col_ind = 0;
        for (int j = 1; j < n; j++)
        {
            if (min_row > mat[i][j])
            {
                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)
        {
           cout << "Value of Saddle Point " << min_row;
           return true;
        }
    }
  
    // If Saddle Point not found
    return false;

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

// Java program to illustrate Saddle point


  
class Test
{
    // Method to find saddle point
    static boolean findSaddlePoint(int mat[][    ], int n)
    {
        // Process all rows one by one
        for (int i = 0; i < n; i++)
        {
            // Find the minimum element of row i.
            // Also find column index of the minimum element
            int min_row = mat[i][0], col_ind = 0;
            for (int j = 1; j < n; j++)
            {
                if (min_row > mat[i][j])
                {
                    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

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#

// C# program to illustrate Saddle point


using System;
  
class GFG {
      
    // Method to find saddle point
    static bool findSaddlePoint(int [,] mat, 
                                int n)
    {
          
        // Process all rows one by one
        for (int i = 0; i < n; i++)
        {
              
            // Find the minimum element of 
            // row i. Also find column index
            // of the minimum element
            int min_row = mat[i, 0], col_ind = 0;
            for (int j = 1; j < n; j++)
            {
                if (min_row > mat[i, j])

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

// PHP program to illustrate


// Saddle point
  
$MAX = 100;
  
// Function to find saddle point
function findSaddlePoint( $mat, $n)
{
    // Process all rows one by one
    for ( $i = 0; $i < $n; $i++)
    {
        // Find the minimum element 
        // of row i. Also find column
        // index of the minimum element
        $min_row = $mat[$i][0]; 
        $col_ind = 0;
        for ( $j = 1; $j < $n; $j++)
        {
            if ($min_row > $mat[$i][$j])
            {
                $min_row = $mat[$i][$j];
                $col_ind = $j;
            }
        }
  
        // Check if the minimum element of 
        // row is also the maximum element
        // of column or not
        $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)
        {
        echo "Value of Saddle Point " ,
                              $min_row;
        return true;
        }
    }
  
    // If Saddle Point not found
    return false;
}

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 :

Value of Saddle Point 7

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

Saddleback Search Algorithm in


a 2D array

Saddleback Search Algorithm in a 2D array - GeeksforGeeks


Find an element in a given matrix such that each row and each column is sorted.
Examples:

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

Output : Element Found at position (0, 0).

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

Below is an efficient solution that works in O(m + n) time.


1) Start with bottom left element
2) Loop: compare this element e with x
….i) if they are equal then return its position
…ii) e x then move it to right (if out of bound of matrix then break return false)
3) repeat the i), ii) and iii) till you find element or returned false
Thanks to devendraiiit for suggesting below approach.
Implementation:

C++

// C++ program to search an element in row-wise


// and column-wise sorted matrix
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
  
/* Searches the element x in mat[m][n]. If the 
   element is found, then prints its position 
   and returns true, otherwise prints "not found"
   and returns false */
bool search(int mat[][MAX], int m, int n, int x)
{
   int i = m-1, j = 0;  //set indexes for bottom left element
   while ( i >= 0 && j < n )
   {
      if ( mat[i][j] == x )
         return true;
      if ( mat[i][j] > x )
        i--;
      else //  if mat[i][j] < x
        j++;
   }
     
   return false;
}
  
// driver program to test above function
int main()
{
  int mat[][MAX] = { {10, 20, 30, 40},
                     {15, 25, 35, 45},
                     {27, 29, 37, 48},
                     {32, 33, 39, 50},
                     {50, 60, 70, 80},
                  };

1976
Chapter 289. Saddleback Search Algorithm in a 2D array

  if (search(mat, 5, 4, 29))


      cout << "Yes";
  else
      cout << "No";
  return 0;
}

Java

// Java program to search an 


// element in row-wise and 
// column-wise sorted matrix
  
class GFG
{
static final int MAX = 100;
  
/* Searches the element x 
in mat[m][n]. If the element 
is found, then prints its 
position and returns true, 
otherwise prints "not found"
and returns false */
static boolean search(int mat[][], int m, 
                      int n, int x)
{
      
    // set indexes for
    // bottom left element
    int i = m - 1, j = 0; 
        while (i >= 0 && j < n)
        {
            if (mat[i][j] == x)
                return true;
            if (mat[i][j] > x)
                i--;
            else // if mat[i][j] < x
                j++;
        }
          
        return false;
}
  
// Driver Code
public static void main(String args[])
{
int mat[][] = {{10, 20, 30, 40},
               {15, 25, 35, 45},

1977
Chapter 289. Saddleback Search Algorithm in a 2D array

               {27, 29, 37, 48},


               {32, 33, 39, 50},
               {50, 60, 70, 80}};
if (search(mat, 5, 4, 29))
    System.out.println("Yes");
else
    System.out.println("No");
}
}
  
// This code is contributed
// by Kirti_Mangal

C#

// C# program to search an 


// element in row-wise and 
// column-wise sorted matrix
using System;
  
class GFG
{
  
/* Searches the element x 
in mat[m][n]. If the element 
is found, then prints its 
position and returns true, 
otherwise prints "not found"
and returns false */
static bool search(int[,] mat, int m, 
                   int n, int x)
{
      
    // set indexes for
    // bottom left element
    int i = m - 1, j = 0; 
        while (i >= 0 && j < n)
        {
            if (mat[i, j] == x)
                return true;
            if (mat[i, j] > x)
                i--;
            else // if mat[i][j] < x
                j++;
        }
          
        return false;
}

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

Time Complexity: O(m + n)


The above can also be implemented by starting from top right corner. Please see search in
a row wise and column wise sorted matrix for the alternate implementation.
Improved By : Kirti_Mangal, Abby_akku

Source

https://www.geeksforgeeks.org/saddleback-search-algorithm-in-a-2d-array/

1979
Chapter 290

Search a Word in a 2D Grid of


characters

Search a Word in a 2D Grid of characters - GeeksforGeeks


Given a 2D grid of characters and a word, find all occurrences of given word in grid. A word
can be matched in all 8 directions at any point. Word is said be found in a direction if all
characters match in this direction (not in zig-zag form).
The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up and 4 Diagonal
directions.
Example:

Input: grid[][] = {"GEEKSFORGEEKS",


"GEEKSQUIZGEEK",
"IDEQAPRACTICE"};
word = "GEEKS"

Output: pattern found at 0, 0


pattern found at 0, 8
pattern found at 1, 0

Input: grid[][] = {"GEEKSFORGEEKS",


"GEEKSQUIZGEEK",
"IDEQAPRACTICE"};
word = "EEE"

Output: pattern found at 0, 2


pattern found at 0, 10
pattern found at 2, 2
pattern found at 2, 12

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.

Source: Microsoft Interview Question


The idea used here is simple, we check every cell. If cell has first character, then we one
by one try all 8 directions from that cell for a match. Implementation is interesting though.
We use two arrays x[] and y[] to find next move in all 8 directions.
Below is C++ implementation of the same.

// C++ programs to search a word in a 2D grid


#include<bits/stdc++.h>
using namespace std;
  
// Rows and columns in given grid
#define R 3
#define C 14
  
// For searching in all 8 direction
int x[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
int y[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
  
// This function searches in all 8-direction from point
// (row, col) in grid[][]

1981
Chapter 290. Search a Word in a 2D Grid of characters

bool search2D(char grid[R][C], int row, int col, string word)


{
    // If first character of word doesn't match with
    // given starting point in grid.
    if (grid[row][col] != word[0])
      return false;
  
    int len = word.length();
  
    // Search word in all 8 directions starting from (row,col)
    for (int dir = 0; dir < 8; dir++)
    {
        // Initialize starting point for current direction
        int k, rd = row + x[dir], cd = col + y[dir];
  
        // First character is already checked, match remaining
        // characters
        for (k = 1; k < len; k++)
        {
            // If out of bound break
            if (rd >= R || rd < 0 || cd >= C || cd < 0)
                break;
  
            // If not matched,  break
            if (grid[rd][cd] != word[k])
                break;
  
            //  Moving in particular direction
            rd += x[dir], cd += y[dir];
        }
  
        // If all character matched, then value of must
        // be equal to length of word
        if (k == len)
            return true;
    }
    return false;
}
  
//  Searches given word in a given matrix in all 8 directions
void patternSearch(char grid[R][C], string word)
{
    // Consider every point as starting point and search
    // given word
    for (int row = 0; row < R; row++)
       for (int col = 0; col < C; col++)
          if (search2D(grid, row, col, word))
             cout << "pattern found at " << row << ", "

1982
Chapter 290. Search a Word in a 2D Grid of characters

                  << col << endl;


}
  
// Driver program
int main()
{
    char grid[R][C] = {"GEEKSFORGEEKS",
                       "GEEKSQUIZGEEK",
                       "IDEQAPRACTICE"
                      };
  
    patternSearch(grid, "GEEKS");
    cout << endl; 
    patternSearch(grid, "EEE");
    return 0;
}

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

Search element in a sorted


matrix

Search element in a sorted matrix - GeeksforGeeks


Given a sorted matrix mat[n][m] and an element ‘x’. Find position of x in the matrix if it is
present, else print -1. Matrix is 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 or equal to the last element of row ’i-1’. The approach should have O(log n + log m)
time complexity. Examples:

Input : mat[][] = { {1, 5, 9},


{14, 20, 21},
{30, 34, 43} }
x = 14
Output : Found at (1, 0)

Input : mat[][] = { {1, 5, 9, 11},


{14, 20, 21, 26},
{30, 34, 43, 50} }
x = 42
Output : -1

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

Another efficient approach that doesn’t require typecasting is explained below.

1) Perform binary search on the middle column


till only two elements are left or till the
middle element of some row in the search is
the required element 'x'. This search is done
to skip the rows that are not required
2) The two left elements must be adjacent. Consider
the rows of two elements and do following
a) check whether the element 'x' equals to the
middle element of any one of the 2 rows
b) otherwise according to the value of the
element 'x' check whether it is present in
the 1st half of 1st row, 2nd half of 1st row,
1st half of 2nd row or 2nd half of 2nd row.

Note: This approach works for the matrix n x m


where 2 <= n. The algorithm can be modified
for matrix 1 x m, we just need to check whether
2nd row exists or not

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}

According the value of 'x' it will be searched in the


2nd half of 1st row = {3, 4} and found at (i, j): (0, 2)

C++

1985
Chapter 291. Search element in a sorted matrix

// C++ implementation to search an element in a


// sorted matrix
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// 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]
void binarySearch(int mat[][MAX], 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)
        {
            cout << "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
    cout << "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
void sortedMatrixSearch(int mat[][MAX], int n,
                                  int m, int x)
{
    // Single row matrix
    if (n == 1)
    {
        binarySearch(mat, 0, 0, m-1, x);
        return;
    }

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

    // search element on 2nd half of 2nd row


    else
        binarySearch(mat, i_low+1, j_mid+1, m-1, x);
}
  
// Driver program to test above
int main()
{
    int n = 4, m = 5, x = 8;
    int mat[][MAX] = {{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);
    return 0;
}

Java

// java implementation to search 


// an element in a sorted matrix
import java.io.*;
  
class GFG 
{
    static int MAX = 100;
      
    // 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)
            {
                System.out.println ( "Found at (" + i 
                                     + ", " + j_mid +")");
                return;
            }
      
            else if (mat[i][j_mid] > x)
                j_high = j_mid - 1;

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

        // the mid of the two rows


        if (mat[i_low][j_mid] == x)
            System.out.println ( "Found at (" + i_low + ","
                                 + j_mid +")");
        else if (mat[i_low + 1][j_mid] == x)
            System.out.println ( "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);
    }
      
    // 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 vt_m

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

Search in a row wise and


column wise sorted matrix

Search in a row wise and column wise sorted matrix - GeeksforGeeks


Given an n x n matrix and a number x, find the position of x in the matrix if it is present
in it. Otherwise, print “Not Found”. In the given matrix, every row and column is sorted
in increasing order. The designed algorithm should have linear time complexity.
Example :

Input : mat[4][4] = { {10, 20, 30, 40},


{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 29
Output : Found at (2, 1)

Input : mat[4][4] = { {10, 20, 30, 40},


{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 100
Output : Element not found

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

Let x = element we're trying to search for in the matrix,


e = current element we're processing in the array.
1) Start with top right element.
2) Loop: compare this element e with x
...i) if e = x, then return position of e, since we found x in the given matrix.
...ii) if e > x then move left to check elements smaller than e (if out of bound of matrix, then
...iii) if e < x then move below to check elements greater than e (if out of bound of matrix, the
3) repeat the i), ii) and iii) until you find the element or return false

Thanks to devendraiiit for suggesting below approach.


Implementation:

C++

// C++ program to search an element in row-wise


// and column-wise sorted matrix
#include <bits/stdc++.h>
  
using namespace std;
  
/* 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 */
int search(int mat[4][4], int n, int x)
{
int i = 0, j = n-1; //set indexes for top right element
while ( i < n && j >= 0 )
{
    if ( mat[i][j] == x )
    {
        cout << "n Found at "
            << i << ", " << j;
        return 1;
    }
    if (mat[i][j] > x )
        j--;
    else // if mat[i][j] < x
        i++;
}
  
cout << "n Element not found";
return 0; // if ( i==n || j== -1 )
}
  
// Driver code
int main()

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)

// C program to search an element in row-wise


// and column-wise sorted matrix
#include<stdio.h>
  
/* 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 */
int search(int mat[4][4], int n, int x)
{
int i = 0, j = n-1; //set indexes for top right element
while ( i < n && j >= 0 )
{
    if ( mat[i][j] == x )
    {
        printf("n Found at %d, %d", i, j);
        return 1;
    }
    if ( mat[i][j] > x )
        j--;
    else // if mat[i][j] < x
        i++;
}
  
printf("n Element not found");
return 0; // if ( i==n || j== -1 )
}
  
// driver program to test above function
int main()
{
int mat[4][4] = { {10, 20, 30, 40},
                    {15, 25, 35, 45},

1996
Chapter 292. Search in a row wise and column wise sorted matrix

                    {27, 29, 37, 48},


                    {32, 33, 39, 50},
                };
search(mat, 4, 29);
return 0;
}

Java

// JAVA Code for Search in a row wise and


// column wise sorted matrix
  
class GFG{
  
/* 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 */
    private static void search(int[][] mat, int n, int x) {
          
        int i = 0, j = n-1; //set indexes for top right
                            // element
  
        while ( i < n && j >= 0 )
        {
            if ( mat[i][j] == x )
            {
                System.out.print("n Found at "+ i + " " + j);
                return;
            }
            if ( mat[i][j] > x )
                j--;
            else // if mat[i][j] < x
                i++;
        }
          
        System.out.print("n Element not found");
        return; // if ( i==n || j== -1 )
          
    }
        // driver program to test above function
        public static void main(String[] args) {
        int mat[][] = { {10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {27, 29, 37, 48},
                        {32, 33, 39, 50} };
              
        search(mat, 4, 29);

1997
Chapter 292. Search in a row wise and column wise sorted matrix

        }
          
    }
    // This code is contributed by Arnav Kr. Mandal.

Python3

# Python3 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
def search(mat, n, x):
  
    i = 0
      
    # set indexes for top right element
    j = n - 1
    while ( i < n and j >= 0 ):
      
        if (mat[i][j] == x ):
      
            print("n Found at ", i, ",", j)
            return 1
      
        if (mat[i][j] > x ):
            j -= 1
              
        # if mat[i][j] < x
        else: 
            i += 1
      
    print("Element not found")
    return 0 # if (i == n || j == -1 )
  
# Driver Code
mat= [ [10, 20, 30, 40],
        [15, 25, 35, 45],
        [27, 29, 37, 48],
        [32, 33, 39, 50] ]
search(mat, 4, 29)
  
# This code is contributed by Anant Agarwal.

C#

1998
Chapter 292. Search in a row wise and column wise sorted matrix

// C# Code for Search in a row wise and


// column wise sorted matrix
using System;
  
class GFG
{
    /* 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 */
    private static void search(int[,] mat, 
                            int n, int x) 
    {
        //set indexes for top right
        // element
        int i = 0, j = n - 1; 
  
        while ( i < n && j >= 0 )
        {
            if ( mat[i, j] == x )
            {
                Console.Write("n Found at "
                            + i + ", " + j);
                return;
            }
              
            if (mat[i, j] > x)
                j--;
            else // if mat[i][j] < x
                i++;
        }
          
        Console.Write("n Element not found");
        return; // if ( i==n || j== -1 )
          
    }
        // driver program to test above function
        public static void Main() {
          
        int [,]mat = { {10, 20, 30, 40},
                        {15, 25, 35, 45},
                        {27, 29, 37, 48},
                        {32, 33, 39, 50} };
              
        search(mat, 4, 29);
        }
}
  

1999
Chapter 292. Search in a row wise and column wise sorted matrix

// This code is contributed by Sam007

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

Time Complexity: O(n)


The above approach will also work for m x n matrix (not only for n x n). Complexity would
be O(m + n).
Related Article :
Search element in a sorted matrix
Improved By : ChitraNayal, Abby_akku, code_master5

Source

https://www.geeksforgeeks.org/search-in-row-wise-and-column-wise-sorted-matrix/

2001
Chapter 293

Shift matrix elements row-wise


by k

Shift matrix elements row-wise by k - GeeksforGeeks


Given a square matrix mat[][] and a number k. The task is to shift first k elements of each
row in the right of the matrix.
Examples :

Input : mat[N][N] = {{1, 2, 3},


{4, 5, 6},
{7, 8, 9}}
k = 2
Output :mat[N][N] = {{3, 1, 2}
{6, 4, 5}
{9, 7, 8}}

Input : mat[N][N] = {{1, 2, 3, 4}


{5, 6, 7, 8}
{9, 10, 11, 12}
{13, 14, 15, 16}}
k = 2
Output :mat[N][N] = {{3, 4, 1, 2}
{7, 8, 5, 6}
{11, 12, 9, 10}
{15, 16, 13, 14}}

Note: Matrix should be a square matrix

C++

2002
Chapter 293. Shift matrix elements row-wise by k

// C++ program to shift k elements in a matrix.


#include <bits/stdc++.h>
using namespace std;
#define N 4
  
// Function to shift first k elements of 
// each row of matrix.
void shiftMatrixByK(int mat[N][N], int k)
{
    if (k > N) {
        cout << "shifting is not possible" << endl;
        return;
    }
      
    int j = 0;
    while (j < N) {
          
        // Print elements from index k
        for (int i = k; i < N; i++)
            cout << mat[j][i] << " ";
              
        // Print elements before index k
        for (int i = 0; i < k; i++)
            cout << mat[j][i] << " ";
              
        cout << endl;
        j++;
    }
}
  
// Driver code
int main()
{
    int mat[N][N] = {{1, 2, 3, 4},
                     {5, 6, 7, 8},
                     {9, 10, 11, 12},
                     {13, 14, 15, 16}};
    int k = 2;
      
    // Function call
    shiftMatrixByK(mat, k);
      
    return 0;
}

Java

// Java program to shift k elements in a 

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

# Python3 program to shift k 


# elements in a matrix.
  
N = 4
# Function to shift first k 
# elements of each row of 
# matrix.
def shiftMatrixByK(mat, k):
    if (k > N) :
        print ("shifting is"
            " not possible")
        return
      
    j = 0
    while (j < N) :
          
        # Print elements from
        # index k
        for i in range(k, N):
            print ("{} " . 
            format(mat[j][i]), end="")
              
        # Print elements before
        # index k
        for i in range(0, k):
            print ("{} " . 
            format(mat[j][i]), end="")
              
        print ("")
        j = j + 1
  
# Driver code
mat = [[1, 2, 3, 4],
       [5, 6, 7, 8],
       [9, 10, 11, 12],
       [13, 14, 15, 16]]
k = 2
  
# Function call
shiftMatrixByK(mat, k)
  

2005
Chapter 293. Shift matrix elements row-wise by k

# This code is contributed by 


# Manish Shaw (manishshaw1)

C#

// C# program to shift k elements in a 


// matrix.
using System;
  
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) {
            Console.WriteLine("shifting is"
                        + " not possible");
            return;
        }
          
        int j = 0;
        while (j < N) {
              
            // Print elements from index k
            for (int i = k; i < N; i++)
                Console.Write(mat[j,i] + " ");
                  
            // Print elements before index k
            for (int i = 0; i < k; i++)
                Console.Write(mat[j,i] + " ");
                  
            Console.WriteLine();
            j++;
        }
    }
      
    // Driver code
    public static void Main()
    {
        int [,]mat = new int [,]
                    { {1, 2, 3, 4},
                      {5, 6, 7, 8},
                      {9, 10, 11, 12},
                      {13, 14, 15, 16} };

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

             array(13, 14, 15, 16));


$k = 2;
      
// Function call
shiftMatrixByK($mat, $k);
  
// This code is contributed by 
// Manish Shaw(manishshaw1)
?>

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

Shortest distance between two


cells in a matrix or grid

Shortest distance between two cells in a matrix or grid - GeeksforGeeks


Given a matrix of N*M order. Find the shortest distance from a source cell to a destination
cell, traversing through limited cells only. Also you can move only up, down, left and right.
If found output the distance else -1.
s represents ‘source’
d represents ‘destination’
* represents cell you can travel
0 represents cell you can not travel
This problem is meant for single source and destination.
Examples:

Input : {'0', '*', '0', 's'},


{'*', '0', '*', '*'},
{'0', '*', '*', '*'},
{'d', '*', '*', '*'}
Output : 6

Input : {'0', '*', '0', 's'},


{'*', '0', '*', '*'},
{'0', '*', '*', '*'},
{'d', '0', '0', '0'}
Output : -1

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

2. Start BFS with source cell.


3. Make a visited array with all having “false” values except ‘0’cells which are assigned
“true” values as they can not be traversed.
4. Keep updating distance from source value in each move.
5. Return distance when destination is met, else return -1 (no path exists in between
source and destination).

// C++ Code implementation for above problem


#include <bits/stdc++.h>
using namespace std;
  
#define N 4
#define M 4
  
// QItem for current location and distance
// from source location
class QItem {
public:
    int row;
    int col;
    int dist;
    QItem(int x, int y, int w)
        : row(x), col(y), dist(w)
    {
    }
};
  
int minDistance(char grid[N][M])
{
    QItem source(0, 0, 0);
  
    // To keep track of visited QItems. Marking
    // blocked cells as visited.
    bool visited[N][M];
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++)
        {
            if (grid[i][j] == '0')
                visited[i][j] = true;
            else
                visited[i][j] = false;
  
            // Finding source
            if (grid[i][j] == 's')
            {
               source.row = i;
               source.col = j;
            }

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

Shortest path in a Binary Maze

Shortest path in a Binary Maze - GeeksforGeeks


Given a MxN matrix where each element can either be 0 or 1. We need to find the shortest
path between a given source cell to a destination cell. The path can only be created out of
a cell if its value is 1.
Expected time complexity is O(MN).
For example –

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

The idea is inspired from Lee algorithm and uses BFS.

1. We start from the source cell and calls BFS procedure.


2. We maintain a queue to store the coordinates of the matrix and initialize it with the
source cell.

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.

Below is C++ implementation of the idea –

// C++ program to find the shortest path between


// a given source cell to a destination cell.
#include <bits/stdc++.h>
using namespace std;
#define ROW 9
#define COL 10
  
//to store matrix cell cordinates
struct Point
{
    int x;
    int y;
};
  
// An Data Structure for queue used in BFS
struct queueNode
{
    Point pt;  // The cordinates of a cell
    int dist;  // cell's distance of from the source
};
  
// check whether given cell (row, col) is a valid
// cell or not.
bool isValid(int row, int col)
{
    // return true if row number and column number
    // is in range
    return (row >= 0) && (row < ROW) &&
           (col >= 0) && (col < COL);
}
  
// These arrays are used to get row and column
// numbers of 4 neighbours of a given cell
int rowNum[] = {-1, 0, 0, 1};
int colNum[] = {0, -1, 1, 0};
  
// function to find the shortest path between

2014
Chapter 295. Shortest path in a Binary Maze

// a given source cell to a destination cell.


int BFS(int mat[][COL], Point src, Point dest)
{
    // check source and destination cell
    // of the matrix have value 1
    if (!mat[src.x][src.y] || !mat[dest.x][dest.y])
        return INT_MAX;
  
    bool visited[ROW][COL];
    memset(visited, false, sizeof visited);
      
    // Mark the source cell as visited
    visited[src.x][src.y] = true;
  
    // Create a queue for BFS
    queue<queueNode> q;
      
    // distance of source cell is 0
    queueNode s = {src, 0};
    q.push(s);  // Enqueue source cell
  
    // Do a BFS starting from source cell
    while (!q.empty())
    {
        queueNode curr = q.front();
        Point pt = curr.pt;
  
        // If we have reached the destination cell,
        // we are done
        if (pt.x == dest.x && pt.y == dest.y)
            return curr.dist;
  
        // Otherwise dequeue the front cell in the queue
        // and enqueue its adjacent cells
        q.pop();
  
        for (int i = 0; i < 4; i++)
        {
            int row = pt.x + rowNum[i];
            int col = pt.y + colNum[i];
              
            // if adjacent cell is valid, has path and
            // not visited yet, enqueue it.
            if (isValid(row, col) && mat[row][col] && 
               !visited[row][col])
            {
                // mark cell as visited and enqueue it
                visited[row][col] = true;

2015
Chapter 295. Shortest path in a Binary Maze

                queueNode Adjcell = { {row, col},


                                      curr.dist + 1 };
                q.push(Adjcell);
            }
        }
    }
  
    //return -1 if destination cannot be reached
    return INT_MAX;
}
  
// Driver program to test above function
int main()
{
    int 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 }
    };
  
    Point source = {0, 0};
    Point dest = {3, 4};
  
    int dist = BFS(mat, source, dest);
  
    if (dist != INT_MAX)
        cout << "Shortest Path is " << dist ;
    else
        cout << "Shortest Path doesn't exist";
  
    return 0;
}

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

Solve the Crossword Puzzle

Solve the Crossword Puzzle - GeeksforGeeks


A 10 x 10 Crossword grid is provided, along with a set of words (or names of places)
which need to be filled into the grid. The cells in the grid are initially, either + signs or –
signs. Cells marked with a ‘+’ have to be left as they are. Cells marked with a ‘-‘ need to
be filled up with an appropriate character.
You are also given an array of words that need to be filled in Crossword grid.
Example :

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.

// CPP code to fill the crossword puzzle


#include <bits/stdc++.h>
using namespace std;
  
// ways are to calculate the number of
// possible ways to fill the grid
int ways = 0;
  
// this function is used to print
// the resultant matrix
void printMatrix(vector<string>& matrix, int n)
{
    for (int i = 0; i < n; i++)
        cout << matrix[i] << endl;
}
  
// this function checks for the current word
// if it can be placed horizontally 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> checkHorizontal(int x, int y,
                               vector<string> matrix,
                               string currentWord)
{
    int n = currentWord.length();
  
    for (int i = 0; i < n; i++) {
        if (matrix[x][y + i] == '#' || 
            matrix[x][y + i] == currentWord[i]) {
            matrix[x][y + i] = currentWord[i];
        }
        else {
  
            // this shows that word cannot 
            // be placed horizontally
            matrix[0][0] = '@';
            return matrix;
        }
    }

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

    // take input of puzzle in matrix


    // input of grid of size n1 x n1
    matrix.push_back("*#********");
    matrix.push_back("*#********");
    matrix.push_back("*#****#***");
    matrix.push_back("*##***##**");
    matrix.push_back("*#****#***");
    matrix.push_back("*#****#***");
    matrix.push_back("*#****#***");
    matrix.push_back("*#*######*");
    matrix.push_back("*#********");
    matrix.push_back("***#######");
  
    vector<string> words;
  
    // the words matrix will hold all
    // the words need to be filled in the grid
    words.push_back("PUNJAB");
    words.push_back("JHARKHAND");
    words.push_back("MIZORAM");
    words.push_back("MUMBAI");
  
    // initialize the number of ways
    // to solve the puzzle to zero
    ways = 0;
  
    // recursive function to solve the puzzle
    // Here 0 is the initial index of words array
    // n1 is length of grid
    solvePuzzle(words, matrix, 0, n1);
    cout << "Number of ways to fill the grid is "
         << ways << endl;
  
    return 0;
}

Output:

1 way to solve the puzzle


*J********
*H********
*A****P***
*R#***U#**
*K****N***
*H****J***
*A****A***
*N*MUMBAI*

2022
Chapter 296. Solve the Crossword Puzzle

*D********
***MIZORAM

Number of ways to fill the grid is 1

Source

https://www.geeksforgeeks.org/solve-crossword-puzzle/

2023
Chapter 297

Sort a Matrix in all way


increasing order

Sort a Matrix in all way increasing order - GeeksforGeeks


Given a square matrix of order N*N having distinct elements, the task is to sort given matrix
in such a way that its rows, columns and both diagonals (diagonal and anti-diagonal) are
in increasing order.
Examples:

Input : arr[3][3] = {1, 4, 2,


3, 5, 6,
9, 7, 8}
Output :{1, 2, 3,
4, 5, 6,
7, 8, 9}

Input : arr[2][2] = {0, 4,


5, 2}
Output :{0, 2,
4, 5}

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.

Example: arr[2][2] : {1, 2


3, 4}
Rows in increasing order: {1,2} and {3,4}

2024
Chapter 297. Sort a Matrix in all way increasing order

Columns in increasing order: {1,3} and {2,4}


Diagonal in increasing order: {1,4}
Anti-diagonal in increasing order: {2,3}

// C++ program to sort matrix in all-way


#include<bits/stdc++.h>
using namespace std;
#define N 3
  
// Sorts a matrix in increasing order
void sortAllWay(int arr[][N])
{
    // Consider matrix elements (in row major
    // order) and sort the sequence.
    int *ptr = (int *)arr;
    sort(ptr, ptr+N*N);
}
  
// driver program
int main()
{
    int arr[N][N] = {1, 0, 3,
                     2, 5, 6,
                     9, 4, 8};
    sortAllWay(arr);
  
  
    // print resultant matrix
    for (int i=0; i<N; i++)
    {
        for (int j=0; j<N; j++)
            cout << arr[i][j] << " ";
        cout <<"\n";
    }
  
    return 0;
}

Output:

0 1 2
3 4 5
6 8 9

Time Complexity : O(N*N log N)


Auxiliary Space : (N*N)

2025
Chapter 297. Sort a Matrix in all way increasing order

Source

https://www.geeksforgeeks.org/sort-matrix-way-increasing-order/

2026
Chapter 298

Sort the given matrix

Sort the given matrix - GeeksforGeeks


Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict
order means that matrix is 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
or equal to the last element of row ’i-1’.
Examples:

Input : mat[][] = { {5, 4, 7},


{1, 3, 8},
{2, 9, 6} }
Output : 1 2 3
4 5 6
7 8 9

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++

// C++ implementation to sort the given matrix


#include <bits/stdc++.h>
using namespace std;
  
#define SIZE 10
  
// function to sort the given matrix
void sortMat(int mat[SIZE][SIZE], int n)
{
    // temporary matrix of size n^2

2027
Chapter 298. Sort the given matrix

    int temp[n * n];


    int k = 0;
  
    // copy the elements of matrix one by one
    // into temp[]
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            temp[k++] = mat[i][j];
  
    // sort temp[]
    sort(temp, temp + k);
      
    // copy the elements of temp[] one by one
    // in mat[][]
    k = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            mat[i][j] = temp[k++];
}
  
// function to print the given matrix
void printMat(int mat[SIZE][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 mat[SIZE][SIZE] = { { 5, 4, 7 },
                            { 1, 3, 8 },
                            { 2, 9, 6 } };
    int n = 3;
  
    cout << "Original Matrix:\n";
    printMat(mat, n);
  
    sortMat(mat, n);
  
    cout << "\nMatrix After Sorting:\n";
    printMat(mat, n);
  
    return 0;
}

2028
Chapter 298. Sort the given matrix

Java

// Java implementation to 


// sort the given matrix
import java.io.*;
import java.util.*;
  
class GFG {
      
    static int SIZE = 10;
  
    // function to sort the given matrix
    static void sortMat(int mat[][], int n)
    {
        // temporary matrix of size n^2
        int temp[] = new int[n * n];
        int k = 0;
      
        // copy the elements of matrix 
        // one by one into temp[]
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                temp[k++] = mat[i][j];
      
        // sort temp[]
        Arrays.sort(temp);
          
        // copy the elements of temp[]
        // one by one in mat[][]
        k = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                mat[i][j] = temp[k++];
    }
      
    // function to print the given matrix
    static void printMat(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
    public static void main(String args[])
    {

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

# Python3 implementation to sort


# the given matrix
  
SIZE = 10
  
# Function to sort the given matrix
def sortMat(mat, n) :
      
    # Temporary matrix of size n^2
    temp = [0] * (n * n)
    k = 0
  
    # Copy the elements of matrix  
    # one by one into temp[]
    for i in range(0, n) :
          
        for j in range(0, n) :
              
            temp[k] = mat[i][j]
            k += 1
  
    # sort temp[]
    temp.sort()
      
    # copy the elements of temp[] 
    # one by one in mat[][]
    k = 0
      

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

        // temporary matrix of size n^2


        int[] temp = new int[n * n];
        int k = 0;
  
        // copy the elements of matrix
        // one by one into temp[]
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                temp[k++] = mat[i, j];
  
        // sort temp[]
        Array.Sort(temp);
  
        // copy the elements of temp[]
        // one by one in mat[][]
        k = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
            mat[i, j] = temp[k++];
    }
  
    // function to print the given 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.WriteLine();
        }
    }
  
    // Driver code
    public static void Main()
    {
        int[, ] mat = { { 5, 4, 7 },
                        { 1, 3, 8 },
                        { 2, 9, 6 } };
        int n = 3;
  
        Console.WriteLine("Original Matrix:");
        printMat(mat, n);
  
        sortMat(mat, n);
  
        Console.WriteLine("Matrix After Sorting:");
        printMat(mat, n);
    }
}

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

Matrix After Sorting:


1 2 3
4 5 6
7 8 9

Time Complexity: O(n2 log2 n).


Auxiliary Space: O(n2 ).

Source

https://www.geeksforgeeks.org/sort-given-matrix/

2033
Chapter 299

Sort the matrix row-wise and


column-wise

Sort the matrix row-wise and column-wise - GeeksforGeeks


Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.
Examples:

Input : mat[][] = { {4, 1, 3},


{9, 6, 8},
{5, 2, 7} }
Output : 1 3 4
2 5 7
6 8 9

Input : mat[][] = { {12, 7, 1, 8},


{20, 9, 11, 2},
{15, 4, 5, 13},
{3, 18, 10, 6} }
Output : 1 5 8 12
2 6 10 15
3 7 11 18
4 9 13 20

Approach: Following are the steps:

1. Sort each row of the matrix.


2. Get transpose of the matrix.
3. Again sort each row of the matrix.
4. Again get transpose of the matrix.

2034
Chapter 299. Sort the matrix row-wise and column-wise

Algorithm for sorting each row of matrix using C++ STL sort():

for (int i = 0 ; i < n; i++)


sort(mat[i], mat[i] + n);

Algorithm for getting transpose of the matrix:

for (int i = 0; i < n; i++) {


for (int j = i + 1; i < n; i++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}

C++

// C++ implementation to sort the matrix row-wise


// and column-wise
#include <bits/stdc++.h>
  
using namespace std;
  
#define MAX_SIZE 10
  
// function to sort each row of the matrix
void sortByRow(int mat[MAX_SIZE][MAX_SIZE], int n)
{
    for (int i = 0; i < n; i++)
  
        // sorting row number 'i'
        sort(mat[i], mat[i] + n);
}
  
// function to find transpose of the matrix
void transpose(int mat[MAX_SIZE][MAX_SIZE], 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)
            swap(mat[i][j], mat[j][i]);
}
  

2035
Chapter 299. Sort the matrix row-wise and column-wise

// function to sort the matrix row-wise


// and column-wise
void sortMatRowAndColWise(int mat[MAX_SIZE][MAX_SIZE],
                                               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
void printMat(int mat[MAX_SIZE][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 mat[MAX_SIZE][MAX_SIZE] = { { 4, 1, 3 },
                            { 9, 6, 8 },
                            { 5, 2, 7 } };
    int n = 3;
  
    cout << "Original Matrix:\n";
    printMat(mat, n);
  
    sortMatRowAndColWise(mat, n);
  
    cout << "\nMatrix After Sorting:\n";
    printMat(mat, n);
  
    return 0;
}

Java

2036
Chapter 299. Sort the matrix row-wise and column-wise

// Java implementation to sort the 


// matrix row-wise and column-wise
import java.util.Arrays;
  
class GFG
{
    static final int MAX_SIZE=10;
      
    // function to sort each row of the matrix
    static void sortByRow(int mat[][], int n)
    {
        for (int i = 0; i < n; i++)
      
            // sorting row number 'i'
            Arrays.sort(mat[i]);
    }
      
    // function to find transpose of the matrix
    static void transpose(int 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(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);
    }
      

2037
Chapter 299. Sort the matrix row-wise and column-wise

    // 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++)
                System.out.print(mat[i][j] + " ");
            System.out.println();
        }
    } 
      
    // Driver code 
    public static void main (String[] args)
    {
        int mat[][] = { { 4, 1, 3 },
                        { 9, 6, 8 },
                        { 5, 2, 7 } };
        int n = 3;
      
        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.

Python 3

# Python 3 implementation to 


# sort the matrix row-wise
# and column-wise
MAX_SIZE = 10
  
# function to sort each
# row of the matrix
def sortByRow(mat, n):
    for i in range (n):
          
        # sorting row number 'i'
        for j in range(n-1):
            if mat[i][j] > mat[i][j + 1]:
                temp = mat[i][j]
                mat[i][j] = mat[i][j + 1]
                mat[i][j + 1] = temp

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#

// C# implementation to sort the 


// matrix row-wise and column-wise
using System;
  
class GFG

    // function to sort each
    // row of the matrix
    static void sortByRow(int [,]mat, 
                          int n)
    {
          
    // sorting row number 'i'
    for (int i = 0; i < n ; i++)
        {
        for(int j = 0; 
                j < n - 1; j++)
        {
            if(mat[i, j] > mat[i, j + 1])
            {
              
                var temp = mat[i, j];
                mat[i, j] = mat[i, j + 1];
                mat[i, j + 1] = temp;
                  
            }
        }
        }
    }
      
    // function to find transpose
    // of the matrix
    static void transpose(int [,]mat,
                          int n)
    {
        for (int i = 0; i < n; i++)
            for (int j = i + 1; 
                     j < n; j++) 
                {

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

Matrix After Sorting:


1 3 4
2 5 7
6 8 9

Time Complexity: O(n2 log2 n).


Auxiliary Space: O(1).
Improved By : ChitraNayal

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

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 :

Input : a[3][3] = {{1, 2, 3},


{4, 5, 6},
{7, 8, 9}};
Output : 7 8 9
4 5 6
1 2 3

Input : a[3][3] = {{3, 2, 1},


{9, 8, 7},
{6, 5, 4}};
Output : 7 8 9
4 5 6
1 2 3

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++

// C++ implementation to sort the rows


// of matrix in ascending order followed by
// sorting the columns in descending order
#include <bits/stdc++.h>
using namespace std;
  
#define MAX_SIZE 10
  
// function to sort each row of the matrix
// according to the order specified by 
// ascending.
void sortByRow(int mat[][MAX_SIZE], int n, 
                           bool ascending)
{
    for (int i = 0; i < n; i++)
    {
      if (ascending)    
        sort(mat[i], mat[i] + n);
      else
          sort(mat[i], mat[i] + n, greater<int>());
    }      
}
  
// function to find transpose of the matrix
void transpose(int mat[][MAX_SIZE], 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)
            swap(mat[i][j], mat[j][i]);
}
  
// function to sort the matrix row-wise
// and column-wise
void sortMatRowAndColWise(int mat[][MAX_SIZE],
                                       int n)
{
    // sort rows of mat[][]
    sortByRow(mat, n, true);
  
    // get transpose of mat[][]
    transpose(mat, n);
  
    // again sort rows of mat[][] in descending

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

// Java implementation to sort the rows


// of matrix in ascending order followed by
// sorting the columns in descending order
import java.util.Arrays;
import java.util.Collections;
  
class GFG
{
    static int MAX_SIZE=10;

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

# Python implementation to sort the rows


# of matrix in ascending order followed by
# sorting the columns in descending order
  
MAX_SIZE=10
   
# function to sort each row of the matrix
# according to the order specified by 
# ascending.
def sortByRow(mat, n, ascending):
  
    for i in range(n):
        if (ascending):    

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

Matrix After Sorting:


7 8 9
4 5 6
1 2 3

Source

https://www.geeksforgeeks.org/sorting-rows-matrix-ascending-order-followed-sorting-columns-descending-order/

2051
Chapter 301

Sparse Matrix Representations |


Set 3 ( CSR )

Sparse Matrix Representations | Set 3 ( CSR ) - GeeksforGeeks


If most of the elements in the matrix are zero then the matrix is called a sparse matrix. It
is wasteful to store the zero elements in the matrix since they do not affect the results of
our computation. This is why we implement these matrices in more efficient representations
than the standard 2D Array. Using more efficient representations we can cut down space
and time complexities of operations significantly.
We have discussed at 4 different representations in following articles :

1. Sparse Matrix Representation | Set 1


2. Sparse Matrix Representation | Set 2.

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

Solution: When the matrix is read row by


row, the A vector is [ 5 8 3 6]
The JA vector stores column indices
of elements in A hence, JA = [ 0 1 2
1]. IA[0] = 0. IA[1] = IA[0] + no
of non-zero elements in row 0
i.e 0 + 0 = 0.
Similarly,
IA[2] = IA[1] + 2 = 2
IA[3] = IA[2] + 1 = 3
IA[4] = IA[3]+1 = 4
Therefore IA = [0 0 2 3 4]
The trick is remember that IA[i]
stores NNZ upto and not-including
i row.

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

Output : A = [10 20 30 4 50 60 70 80],


IA = [0 2 4 7 8]
JA = [0 1 1 3 2 3 4 5]

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 )

Step 5: for J = 0 ... N-1


Step 5: If MATRIX [I][J] is not zero
Add MATRIX[I][J] to A
Add J to JA
NNZ = NNZ + 1
[End of IF]
Step 6: Add NNZ to IA
[ End of J loop ]
[ End of I loop ]
Step 7: Print vectors A, IA, JA
Step 8: END

// CPP program to find sparse matrix rep-


// resentation using CSR
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
typedef std::vector<int> vi;
  
typedef vector<vector<int> > matrix;
  
// Utility Function to print a Matrix
void printMatrix(const matrix& M)
{
    int m = M.size();
    int n = M[0].size();
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) 
            cout << M[i][j] << " ";        
        cout << endl;
    }
}
  
// Utility Function to print A, IA, JA vectors
// with some decoration.
void printVector(const vi& V, char* msg)
{
  
    cout << msg << "[ ";
    for_each(V.begin(), V.end(), [](int a) {
        cout << a << " ";
    });
    cout << "]" << endl;
}
  
// Generate the three vectors A, IA, JA 

2054
Chapter 301. Sparse Matrix Representations | Set 3 ( CSR )

void sparesify(const matrix& M)


{
    int m = M.size();
    int n = M[0].size(), i, j;
    vi A;
    vi IA = { 0 }; // IA matrix has N+1 rows
    vi JA;
    int NNZ = 0;
  
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            if (M[i][j] != 0) {
                A.push_back(M[i][j]);
                JA.push_back(j);
  
                // Count Number of Non Zero 
                // Elements in row i
                NNZ++;
            }
        }
        IA.push_back(NNZ);
    }
  
    printMatrix(M);
    printVector(A, (char*)"A = ");
    printVector(IA, (char*)"IA = ");
    printVector(JA, (char*)"JA = ");
}
  
// Driver code
int main()
{
    matrix M = {
        { 0, 0, 0, 0, 1 },
        { 5, 8, 0, 0, 0 },
        { 0, 0, 3, 0, 0 },
        { 0, 6, 0, 0, 1 },
    };
  
    sparesify(M);
  
    return 0;
}

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.

• CSR matrices are memory efficient as long as


.
• Similar to CSR there exits CSC which stands for Compressed Sparse Columns. It is
the column analogue for CSR.
• The ‘New’ Yale format further compresses the A and JA vectors into 1 vector.

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)

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

Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes


in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-
zero elements, we only store non-zero elements. This means storing non-zero elements with
triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common repre-
sentations:

2057
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)

1. Array representation
2. Linked list representation

Method 1: Using Arrays


2D array is used to represent a sparse matrix in which there are three rows named as

• Row: Index of row, where non-zero element is located


• Column: Index of column, where non-zero element is located
• Value: Value of the non zero element located at index – (row,column)

// C++ program for Sparse Matrix Representation


// using Array
#include<stdio.h>
  
int main()
{
    // Assume 4x5 sparse matrix
    int sparseMatrix[4][5] =
    {
        {0 , 0 , 3 , 0 , 4 },
        {0 , 0 , 5 , 7 , 0 },
        {0 , 0 , 0 , 0 , 0 },
        {0 , 2 , 6 , 0 , 0 }
    };
  
    int size = 0;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            if (sparseMatrix[i][j] != 0)
                size++;
  
    // number of columns in compactMatrix (size) must be
    // equal to number of non - zero elements in
    // sparseMatrix

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

Method 2: Using Linked Lists


In linked list, each node has four fields. These four fields are defined as:

• Row: Index of row, where non-zero element is located


• Column: Index of column, where non-zero element is located
• Value: Value of the non zero element located at index – (row,column)
• Next node: Address of the next node

2059
Chapter 302. Sparse Matrix and its representations | Set 1 (Using Arrays and Linked
Lists)

// C program for Sparse Matrix Representation


// using Linked Lists
#include<stdio.h>
#include<stdlib.h>
  
// Node to represent sparse matrix
struct Node
{
    int value;
    int row_position;
    int column_postion;
    struct Node *next;
};
  
// Function to create new node
void create_new_node(struct Node** start, int non_zero_element,
                     int row_index, int column_index )
{
    struct Node *temp, *r;
    temp = *start;
    if (temp == NULL)
    {
        // Create new node dynamically
        temp = (struct Node *) malloc (sizeof(struct Node));
        temp->value = non_zero_element;
        temp->row_position = row_index;
        temp->column_postion = column_index;
        temp->next = NULL;
        *start = temp;

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)

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

List of Lists (LIL)


One of the possible representation of sparse matrix is List of Lists (LIL). Where one list
is used to represent the rows and each row contains the list of triples: Column index,
Value(non – zero element) and address field, for non – zero elements. For the best
performance both lists should be stored in order of ascending keys.

2063
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)

// C program for Sparse Matrix Representation


// using List Of Lists
#include<stdio.h>
#include<stdlib.h>
#define R 4
#define C 5
  
// Node to represent row - list
struct row_list
{
    int row_number;
    struct row_list *link_down;
    struct value_list *link_right;
};
  
// Node to represent triples
struct value_list
{
    int column_index;
    int value;
    struct value_list *next;
};
  
// Fuction to create node for non - zero elements
void create_value_node(int data, int j, struct row_list **z)
{
    struct value_list *temp, *d;
  

2064
Chapter 303. Sparse Matrix and its representations | Set 2 (Using List of Lists and
Dictionary of keys)

    // Create new node dynamically


    temp = (struct value_list*)malloc(sizeof(struct value_list));
    temp->column_index = j+1;
    temp->value = data;
    temp->next = NULL;
  
    // Connect with row list
    if ((*z)->link_right==NULL)
        (*z)->link_right = temp;
    else
    {
        // d points to data list node
        d = (*z)->link_right;
        while(d->next != NULL)
            d = d->next;
        d->next = temp;
    }
}
  
// Function to create row list
void create_row_list(struct row_list **start, int row,
                    int column, int Sparse_Matrix[R][C])
{
    // For every row, node is created
    for (int i = 0; i < row; i++)
    {
        struct row_list *z, *r;
  
        // Create new node dynamically
        z = (struct row_list*)malloc(sizeof(struct row_list));
        z->row_number = i+1;
        z->link_down = NULL;
        z->link_right = NULL;
        if (i==0)
            *start = z;
        else
        {
            r = *start;
            while (r->link_down != NULL)
                r = r->link_down;
            r->link_down = z;
        }
  
        // Firstiy node for row is created,
        // and then travering is done in that row
        for (int j = 0; j < 5; j++)
        {
            if (Sparse_Matrix[i][j] != 0)

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

// C++ program for Sparse Matrix Representation


// using Dictionary
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 5
  
// Driver of the program
int main()
{
    // Assume 4x5 sparse matrix
    int Sparse_Matrix[R][C] =
    {
        {0 , 0 , 3 , 0 , 4 },

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

Spiral Pattern - GeeksforGeeks


Given a number N, the task is to print the following pattern:-
Examples:

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++

// C++ program to print the


// spiral pattern

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

    // print the pattern


    for (i = 0; i < row; i++) {
        for (j = 0; j < column; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
  
// Driver code
int main()
{
    int n = 5;
    pattern(n);
    return 0;
}

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

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–;
}
}
// print the pattern
for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { Console.Write(arr[i, j] + ” ”); }
Console.Write(”\n”); } } // Driver code public static void Main() { int n = 5; pattern(n);
} } // This code is contributed // by ChitraNayal [tabby title=”PHP”] = $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–;
}
}
// print the pattern
for ($i = 0; $i < $row; $i++) { for ($j = 0; $j < $column; $j++) { echo $arr[$i][$j] . ”
”; } echo ”\n”; } } // Driver code $n = 5; pattern($n); // This code is contributed // by
ChitraNayal ?>
Output:

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

Squares of Matrix Diagonal


Elements

Squares of Matrix Diagonal Elements - GeeksforGeeks


You have given an integer matrix with odd dimensions. Find the square of the diagonals
elements on both sides.
Examples:

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++

// Simple CPP program to print squares of


// diagonal elements.
#include <iostream>
using namespace std;
  

2076
Chapter 305. Squares of Matrix Diagonal Elements

#define MAX 100


  
// function of diagonal square
void diagonalsquare(int mat[][MAX], int row, 
                                  int column)
{
    // This loop is for finding square of first 
    // diagonal elements
    cout << "Diagonal one : ";
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < column; j++)
  
            // if this condition will become true 
            // then we will get diagonal element
            if (i == j)
  
                // printing square of diagonal element
                cout << mat[i][j] * mat[i][j] << " ";
    }
  
    // This loop is for finding square of second 
    // side of diagonal elements
    cout << " \n\nDiagonal two : ";
    for (int i = 0; i < row; i++)
    {
        for (int 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
                cout << mat[i][j] * mat[i][j] << "  ";
    }
}
  
// Driver code
int main()
{
    int mat[][MAX] = { { 2, 5, 7 },
                       { 3, 7, 2 }, 
                       { 5, 6, 9 } };
    diagonalsquare(mat, 3, 3);
    return 0;
}

2077
Chapter 305. Squares of Matrix Diagonal Elements

Java

// Simple JAva program to print squares of


// diagonal elements.
import java.io.*;
  
class GFG
{
    static int MAX =100;
      
    // function of diagonal square
    static void diagonalsquare(int mat[][], int row, 
                                         int column)
    {
        // This loop is for finding square of first 
        // diagonal elements
        System.out.print( "Diagonal one : ");
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < column; j++)
      
                // if this condition will become true 
                // then we will get diagonal element
                if (i == j)
      
                    // printing square of diagonal element
                    System.out.print ( mat[i][j] * mat[i][j] +" ");
        }
        System.out.println();
      
        // This loop is for finding square of second 
        // side of diagonal elements
        System.out.print("Diagonal two : ");
        for (int i = 0; i < row; i++)
        {
            for (int 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
                    System.out.print(mat[i][j] * mat[i][j] +" ");
        }
    }
      
    // Driver code

2078
Chapter 305. Squares of Matrix Diagonal Elements

    public static void main (String[] args) 


    {
        int mat[][] = { { 2, 5, 7 },
                        { 3, 7, 2 }, 
                        { 5, 6, 9 } };
        diagonalsquare(mat, 3, 3);
          
    }
}
  
// This code is contributed by vt_m.

Python3

# Simple Python program 


# to print squares
# of diagonal elements.
  
# function of diagonal square
def diagonalsquare(mat, row, column) :
  
    # This loop is for finding square
    # of first diagonal elements
    print ("Diagonal one : ", end = "")
    for i in range(0, row) :
        for j in range(0, column) :
  
            # if this condition will 
            # become true then we will
            # get diagonal element
            if (i == j) : 
                # printing square of 
                # diagonal element
                print ("{} ".format(mat[i][j] * 
                                    mat[i][j]), end = "")
  
    # This loop is for finding 
    # square of second side 
    # of diagonal elements
    print (" \n\nDiagonal two : ", end = "")
    for i in range(0, row) :
        for j in range(0, column) :
  
            # if this condition will become
            # true then we will get second
            # side diagonal element
            if (i + j == column - 1) :
  

2079
Chapter 305. Squares of Matrix Diagonal Elements

                # printing square of diagonal


                # element
                print ("{} ".format(mat[i][j] * 
                                    mat[i][j]), end = "")
  
  
# Driver code
mat = [[ 2, 5, 7 ],
        [ 3, 7, 2 ], 
        [ 5, 6, 9 ]]
diagonalsquare(mat, 3, 3)
  
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// Simple C# program to print squares of


// diagonal elements.
using System;
  
class GFG
{
    //static int MAX =100;
      
    // function of diagonal square
    static void diagonalsquare(int [,]mat, int row, 
                                        int column)
    {
          
        // This loop is for finding
        // square of first 
        // diagonal elements
        Console.Write( "Diagonal one : ");
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < column; j++)
      
                // if this condition will become true 
                // then we will get diagonal element
                if (i == j)
      
                    // printing square of diagonal element
                    Console.Write ( mat[i,j] * mat[i,j] +" ");
        }
        Console.WriteLine();
      
        // This loop is for finding 

2080
Chapter 305. Squares of Matrix Diagonal Elements

        // square of second side of


        // diagonal elements
        Console.Write("Diagonal two : ");
        for (int i = 0; i < row; i++)
        {
            for (int 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
                    Console.Write(mat[i,j] * mat[i,j] +" ");
        }
    }
      
    // Driver code
    public static void Main () 
    {
        int [,]mat = {{ 2, 5, 7 },
                      { 3, 7, 2 }, 
                      { 5, 6, 9 }};
        diagonalsquare(mat, 3, 3);
          
    }
}
  
// This code is contributed by anuj_67.

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

Time Complexity O(n * n )


Method 2:
An efficient solution is also same as in naive approach but in this, we are taking only one

2082
Chapter 305. Squares of Matrix Diagonal Elements

loop to find the diagonal element and then we print the square of that element.

C++

// Efficient CPP program to print squares of


// diagonal elements.
#include <iostream>
using namespace std;
  
#define MAX 100
  
// function of diagonal square
void diagonalsquare(int mat[][MAX], int row,
                                 int column)
{
    // This loop is for finding of square of 
    // the first side of diagonal elements
    cout << " \nDiagonal one : ";
    for (int i = 0; i < row; i++)
    {
  
        // printing direct square of diagonal 
        // element there is no need to check 
        // condition
        cout << mat[i][i] * mat[i][i] << " ";
    }
  
    // This loop is for finding square of the 
    // second side of diagonal elements
    cout << " \n\nDiagonal two : ";
    for (int i = 0; i < row; i++)
    {
        // printing direct square of diagonal 
        // element in the second side
        cout << mat[i][row - i - 1] * mat[i][row - i - 1] 
            << " ";
    }
}
  
// Driver code
int main()
{
    int mat[][MAX] = { { 2, 5, 7 },
                    { 3, 7, 2 }, 
                    { 5, 6, 9 } };
    diagonalsquare(mat, 3, 3);
    return 0;
}

2083
Chapter 305. Squares of Matrix Diagonal Elements

Java

// Efficient JAVA program to print squares of


// diagonal elements.
import java.io.*;
  
class GFG 
{
    static int MAX =100;
      
    // function of diagonal square
    static void diagonalsquare(int mat[][], int row, int column)
    {
        // This loop is for finding of square of 
        // the first side of diagonal elements
        System.out.print (" Diagonal one : ");
        for (int i = 0; i < row; i++)
        {
      
            // printing direct square of diagonal 
            // element there is no need to check 
            // condition
            System.out.print( mat[i][i] * mat[i][i] +" ");
        }
        System.out.println();
      
        // This loop is for finding square of the 
        // second side of diagonal elements
        System.out.print( " Diagonal two : ");
        for (int i = 0; i < row; i++)
        {
            // printing direct square of diagonal 
            // element in the second side
            System.out.print( mat[i][row - i - 1] *
                              mat[i][row - i - 1] + " ");
        }
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        int mat[][] = { { 2, 5, 7 },
                        { 3, 7, 2 }, 
                        { 5, 6, 9 } };
        diagonalsquare(mat, 3, 3);
      
    }

2084
Chapter 305. Squares of Matrix Diagonal Elements

  
// This code is contributed by vt_m.

Python3

# Efficient Python program 


# to print squares of 
# diagonal elements.
  
# function of diagonal square
def diagonalsquare(mat, row, 
                   column) :
      
    # This loop is for finding
    # of square of the first 
    # side of diagonal elements
    print ("Diagonal one : ", 
                    end = "")
    for i in range(0, row) : 
  
        # printing direct square 
        # of diagonal element 
        # there is no need to 
        # check condition
        print (mat[i][i] *
               mat[i][i], end = " ")
      
  
    # This loop is for finding 
    # square of the second side
    # of diagonal elements
    print ("\n\nDiagonal two : ",
                        end = "")
      
    for i in range(0, row) :     
          
        # printing direct square 
        # of diagonal element in
        # the second side
        print (mat[i][row - i - 1] *
               mat[i][row - i - 1] , 
                          end = " ") 
  
# Driver code
mat = [[2, 5, 7 ],
       [3, 7, 2 ], 
       [5, 6, 9 ]]
diagonalsquare(mat, 3, 3)

2085
Chapter 305. Squares of Matrix Diagonal Elements

      
# This code is contributed by 
# Manish Shaw(manishshaw1)

C#

// Efficient C# program to print 


// squares of diagonal elements.
using System;
  
class GFG {
      
    static int MAX =100;
      
    // function of diagonal square
    static void diagonalsquare(int [,] mat, 
                               int row, 
                               int column)
    {
          
        // This loop is for finding of 
        // square of the first side of 
        // diagonal elements
        Console.Write ("Diagonal one : ");
          
        for (int i = 0; i < row; i++)
        {
      
            // printing direct square of diagonal 
            // element there is no need to check 
            // condition
            Console.Write(mat[i, i] * 
                          mat[i, i] +" ");
        }
        Console.WriteLine();
      
        // This loop is for finding square 
        // of the second side of diagonal
        // elements
        Console.Write("Diagonal two : ");
        for (int i = 0; i < row; i++)
        {
            // printing direct square of diagonal 
            // element in the second side
            Console.Write(mat[i, row - i - 1] *
                          mat[i, row - i - 1] + " ");
        }
    }

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

Time Complexity O(n)


Improved By : KRV, vt_m, manishshaw1

Source

https://www.geeksforgeeks.org/squares-of-matrix-diagonal-elements/

2088
Chapter 306

Strassen’s Matrix Multiplication


Algorithm | Implementation

Strassen’s Matrix Multiplication Algorithm | Implementation - GeeksforGeeks


The Strassen’s method of matrix multiplication is a typical divide and conquer algorithm.
We have discussed Strassen’s Algorithm here. However, let’s get again on what’s behind the
divide and conquer approach and implement it.
Prerequisite: It is required to see this post before further understanding.
Implementation

// CPP program to implement Strassen’s Matrix 


// Multiplication Algorithm 
#include <bits/stdc++.h>
using namespace std;
typedef long long lld;
  
/* Strassen's Algorithm for matrix multiplication
   Complexity:    O(n^2.808) */
  
inline lld** MatrixMultiply(lld** a, lld** b, int n,
                                      int l, int m)
{
    lld** c = new lld*[n];
    for (int i = 0; i < n; i++)
        c[i] = new lld[m];
  
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            c[i][j] = 0;
            for (int k = 0; k < l; k++) {

2089
Chapter 306. Strassen’s Matrix Multiplication Algorithm | Implementation

                c[i][j] += a[i][k] * b[k][j];


            }
        }
    }
    return c;
}
  
inline lld** Strassen(lld** a, lld** b, int n, 
                                int l, int m)
{
    if (n == 1 || l == 1 || m == 1) 
        return MatrixMultiply(a, b, n, l, m);
  
    lld** c = new lld*[n];
    for (int i = 0; i < n; i++)
        c[i] = new lld[m];
  
    int adjN = (n >> 1) + (n & 1);
    int adjL = (l >> 1) + (l & 1);
    int adjM = (m >> 1) + (m & 1);
  
    lld**** As = new lld***[2];
    for (int x = 0; x < 2; x++) {
        As[x] = new lld**[2];
        for (int y = 0; y < 2; y++) {
            As[x][y] = new lld*[adjN];
            for (int i = 0; i < adjN; i++) {
                As[x][y][i] = new lld[adjL];
                for (int j = 0; j < adjL; j++) {
                    int I = i + (x & 1) * adjN;
                    int J = j + (y & 1) * adjL;
                    As[x][y][i][j] = (I < n && J < l) ? a[I][J] : 0;
                }
            }
        }
    }
  
    lld**** Bs = new lld***[2];
    for (int x = 0; x < 2; x++) {
        Bs[x] = new lld**[2];
        for (int y = 0; y < 2; y++) {
            Bs[x][y] = new lld*[adjN];
            for (int i = 0; i < adjL; i++) {
                Bs[x][y][i] = new lld[adjM];
                for (int j = 0; j < adjM; j++) {
                    int I = i + (x & 1) * adjL;
                    int J = j + (y & 1) * adjM;
                    Bs[x][y][i][j] = (I < l && J < m) ? b[I][J] : 0;

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

                for (int k = 0; k < adjL; k++) {


                    s[i][j][k] = As[0][0][j][k] + As[1][1][j][k];
                }
            }
            break;
        case 5:
            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][0][j][k] + Bs[1][1][j][k];
                }
            }
            break;
        case 6:
            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][1][j][k] - As[1][1][j][k];
                }
            }
            break;
        case 7:
            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[1][1][j][k];
                }
            }
            break;
        case 8:
            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[1][0][j][k];
                }
            }
            break;
        case 9:
            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][0][j][k] + Bs[0][1][j][k];
                }

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

    for (int i = 0; i < 10; i++) {


        switch (i) {
        case 0:
        case 3:
        case 5:
        case 7:
        case 9:
            for (int j = 0; j < adjL; j++) {
                delete[] s[i][j];
            }
            break;
        case 1:
        case 2:
        case 4:
        case 6:
        case 8:
            for (int j = 0; j < adjN; j++) {
                delete[] s[i][j];
            }
            break;
        }
        delete[] s[i];
    }
    delete[] s;
  
    for (int i = 0; i < 7; i++) {
        for (int j = 0; j < (n >> 1); j++) {
            delete[] p[i][j];
        }
        delete[] p[i];
    }
    delete[] p;
  
    return c;
}
  
int main()
{
    lld** matA;
    matA = new lld*[2];
    for (int i = 0; i < 2; i++)
        matA[i] = new lld[3];
    matA[0][0] = 1;
    matA[0][1] = 2;
    matA[0][2] = 3;
    matA[1][0] = 4;
    matA[1][1] = 5;
    matA[1][2] = 6;

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

Submatrix Sum Queries

Submatrix Sum Queries - GeeksforGeeks


Given a matrix of size M x N, there are large number of queries to find submatrix sums.
Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find
out.
How to preprocess the matrix so that submatrix sum queries can be performed in O(1) time.
Example :

tli : Row number of top left of query submatrix


tlj : Column number of top left of query submatrix
rbi : Row number of bottom right of query submatrix
rbj : Column number of bottom right of query submatrix

Input: mat[M][N] = {{1, 2, 3, 4, 6},


{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
Query1: tli = 0, tlj = 0, rbi = 1, rbj = 1
Query2: tli = 2, tlj = 2, rbi = 3, rbj = 4
Query3: tli = 1, tlj = 2, rbi = 3, rbj = 3;

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.

Sum between (tli, tlj) and (rbi, rbj) is,


aux[rbi][rbj] - aux[tli-1][rbj] -
aux[rbi][tlj-1] + aux[tli-1][tlj-1]

The submatrix aux[tli-1][tlj-1] is added because


elements of it are subtracted twice.

Illustration:

mat[M][N] = {{1, 2, 3, 4, 6},


{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };

We first preprocess the matrix and build


following aux[M][N]
aux[M][N] = {1, 3, 6, 10, 16}
{6, 11, 22, 27, 35},
{10, 21, 39, 49, 62},
{12, 27, 53, 72, 89} }

Query : tli = 2, tlj = 2, rbi = 3, rbj = 4

Sum between (2, 2) and (3, 4) = 89 - 35 - 27 + 11


= 38

How to build aux[M][N]?


1. Copy first row of mat[][] to aux[][]
2. Do column wise sum of the matrix and store it.
3. Do the row wise sum of updated matrix aux[][] in step 2.
Below is the program based on above idea.
C++

// C++ program to compute submatrix query sum in O(1)


// time
#include<iostream>
using namespace std;
#define M 4
#define N 5

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

// Java program to compute submatrix query 


// sum in O(1) time
class GFG {
      
    static final int M = 4;
    static final int N = 5;
      
    // 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)
    static int preProcess(int mat[][], int aux[][])
    {
          
        // 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];
          

2099
Chapter 307. Submatrix Sum Queries

        // 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];
                  
        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 (String[] args)
    {
        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];

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#

// C# program to compute submatrix 


// query sum in O(1) time
using System;
  
class GFG

    static int M = 4;
    static int N = 5;
      
    // 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)
    static int preProcess(int [,]mat, int [,]aux)
    {
        // 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++)

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

Sudo Placement 2 | Matrix


Series

Sudo Placement 2 | Matrix Series - GeeksforGeeks


A Matrix series is defined as follows:

M, MT , M(MT ), M(MT )2 , M2 (MT )3 , M3 (MT )5 , M5 (MT )8 . . . . . .


. .,
where M is a binary square matrix of size K x K (Binary Matrix is a special type
of Matrix where each element of the matrix is either 0 or 1) and MT represents
the transpose of Matrix M.

Given N and K, find the Nth term of the series.


Prerequisites : Modular Exponentiation
Examples:

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:

Sk = Mfib(k - 1)(MT) fib(K)

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:

// CPP code to find Kth term of the Matrix Series


#include <bits/stdc++.h>
  
#define ll long long
#define mod 1000000007
  
using namespace std;
  
// This function multiplies two matrices A and B, under modulo mod
// and returns the resultant matrix after multiplication
vector<vector<int> > multiply(vector<vector<int> > A,
                              vector<vector<int> > B)
{
  
    // n is the size of the matrix

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

        vector<vector<int> > MpowerFibKminusOne;


        MpowerFibKminusOne = fastpower(M, n, fibonacci[K - 1]);
  
        vector<vector<int> > MTransposePowerFibK;
        MTransposePowerFibK = fastpower(transposeM, n, fibonacci[K]);
  
        // kthTerm = (M^fib[K - 1]) * (transposeM ^ fib[K])
        vector<vector<int> > kthTerm = multiply(MpowerFibKminusOne,
                                                MTransposePowerFibK);
  
        // Print the Resultant Matrix
        printMatrix(kthTerm);
    }
}
  
// Driver Code
int main()
{
  
    int n, K;
    n = 2;
    K = 4;
    vector<vector<int> > M{ { 1, 1 }, { 0, 1 } };
    getKthTerm(M, n, K);
  
    // prints the 5th term
    K = 5;
    getKthTerm(M, n, K);
  
    return 0;
}
 

Output :

3 1
2 1
7 2
3 1

Source

https://www.geeksforgeeks.org/sudo-placement-2-matrix-series/

2108
Chapter 309

Sudo Placement[1.5] | Wolfish

Sudo Placement[1.5] | Wolfish - GeeksforGeeks


Given a N x N matrix where value at cell (i, j) is the cost of moving from a cell (i, j) to cell
(i – 1, j – 1), (i – 1, j) or (i, j – 1). Your task is to find the maximum cost path from (N – 1,
N – 1) cell to (0, 0) cell in the N x N matrix (0 – based indexing). However, you have some
restrictions on the movement from one cell to the other cell. If you are at (i, j) cell and (i +
j) is a power of 2, you can only move to (i – 1, j – 1) cell. If (i + j) is not a power of 2 then
you can move to (i – 1, j) or (i, j – 1)
Examples:

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

cost = a[m][n] + maxCost(a, m – 1, n – 1)

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:

cost = a[m][n] + max(maxCost(a, m – 1, n), maxCost(a, m, n – 1))

Below is the recursive implementation of the above approach:

// C++ program for


// SP - Wolfish
#include <bits/stdc++.h>
using namespace std;
  
const int size = 1000;
  
// Function to find the maxCost of path from
// (n-1, n-1) to (0, 0) | recursive approach
int maxCost(int a[][size], int m, int n)
{
    // base condition
    if (n < 0 || m < 0)
        return -1e9;
  
    // reaches the point
    else if (m == 0 && n == 0)
        return 0;
  
    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 a[m][n] + maxCost(a, m - 1, n - 1);
  
        // if not a power of 2
        // then move side-wise
        else
            return a[m][n] + max(maxCost(a, m - 1, n),
                                 maxCost(a, m, n - 1));
    }
}
  
// Function to return the maximum cost

2110
Chapter 309. Sudo Placement[1.5] | Wolfish

int answer(int a[][size], int n)


{
    // calling dp function to get the answer
    return maxCost(a, n - 1, n - 1);
}
  
// 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;
}

Time Complexity: O(2N )


Approach using Memoization
In the above recursion, many sub-problems are being repeatedly called. To reduce the
number of repetative calls, memoization has been used. The common point of observation
is that only two parameters value are changing at every function call. So if we memoize the
returned value in a dp[][] array, the number of calls will be reduced to N^2. Hence store the
computed value of every maxCost(m, n) in dp[m][n]. If the maxCost(m, n) is called more
than once, then the extra calls of the fucntion will be reduced by returning the value stored
at dp[m][n].
Below is the efficient implementation of the above approach:

// C++ program for SP - Wolfish


#include <bits/stdc++.h>
using namespace std;
  
const int size = 1000;
  
// Function to find the maxCost of path from
// (n-1, n-1) to (0, 0)
int maxCost(int a[][size], int m, int n, int dp[][size])
{
    // base condition
    if (n < 0 || m < 0)
        return -1e9;
  
    // reaches the point

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

Time Complexity: O(N2 )


Auxiliary Space: O(N2 )
Note: To implement a bottom-up approach, we need to check if ((m+1) + (n+1)) is a
power of 2 or not instead of (m+n) as the moves are in top-down order.

Source

https://www.geeksforgeeks.org/sudo-placement1-5-wolfish/

2113
Chapter 310

Sudoku | Backtracking-7

Sudoku | Backtracking-7 - GeeksforGeeks


Given a partially filled 9×9 2D array ‘grid[9][9]’, the goal is to assign digits (from 1 to 9)
to the empty cells so that every row, column, and subgrid of size 3×3 contains exactly one
instance of the digits from 1 to 9.

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.

Find row, col of an unassigned cell


If there is none, return true
For digits from 1 to 9
a) If there is no conflict for digit at row, col
assign digit to row, col and recursively try fill in rest of grid
b) If recursion successful, return true
c) Else, remove digit and try another
If all digits have been tried and nothing worked, return false

Following are C++ and Python implementation for Sudoku problem. It prints the
completely filled grid as output.

C/C++

// A Backtracking program  in C++ to solve Sudoku problem


#include <stdio.h>
  
// UNASSIGNED is used for empty cells in sudoku grid
#define UNASSIGNED 0
  
// N is used for the size of Sudoku grid. Size will be NxN
#define N 9
  
// This function finds an entry in grid that is still unassigned
bool FindUnassignedLocation(int grid[N][N], int &row, int &col);
  
// Checks whether it will be legal to assign num to the given row, col
bool isSafe(int grid[N][N], int row, int col, int num);
  
/* 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) */
bool SolveSudoku(int grid[N][N])
{
    int row, col;
  
    // If there is no unassigned location, we are done
    if (!FindUnassignedLocation(grid, row, col))
       return true; // success!
  
    // consider digits 1 to 9
    for (int num = 1; num <= 9; num++)
    {

2115
Chapter 310. Sudoku | Backtracking-7

        // if looks promising


        if (isSafe(grid, row, col, num))
        {
            // make tentative assignment
            grid[row][col] = num;
  
            // return, if success, yay!
            if (SolveSudoku(grid))
                return true;
  
            // failure, unmake & try again
            grid[row][col] = UNASSIGNED;
        }
    }
    return false; // this triggers backtracking
}
  
/* Searches the grid to find an entry that is still unassigned. If
   found, the reference parameters row, col will be set the location
   that is unassigned, and true is returned. If no unassigned entries
   remain, false is returned. */
bool FindUnassignedLocation(int grid[N][N], int &row, int &col)
{
    for (row = 0; row < N; row++)
        for (col = 0; col < N; col++)
            if (grid[row][col] == UNASSIGNED)
                return true;
    return false;
}
  
/* Returns a boolean which indicates whether an assigned entry
   in the specified row matches the given number. */
bool UsedInRow(int grid[N][N], int row, int num)
{
    for (int col = 0; col < N; col++)
        if (grid[row][col] == num)
            return true;
    return false;
}
  
/* Returns a boolean which indicates whether an assigned entry
   in the specified column matches the given number. */
bool UsedInCol(int grid[N][N], int col, int num)
{
    for (int row = 0; row < N; row++)
        if (grid[row][col] == num)
            return true;
    return false;

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

    if (SolveSudoku(grid) == true)


          printGrid(grid);
    else
         printf("No solution exists");
  
    return 0;
}

Python

# A Backtracking program  in Pyhton to solve Sudoku problem


  
  
# A Utility Function to print the Grid
def print_grid(arr):
    for i in range(9):
        for j in range(9):
            print arr[i][j],
        print ('n')
  
          
# Function to Find the entry in the Grid that is still  not used
# Searches the grid to find an entry that is still unassigned. If
# found, the reference parameters row, col will be set the location
# that is unassigned, and true is returned. If no unassigned entries
# remain, false is returned.
# 'l' is a list  variable that has been passed from the solve_sudoku function
# to keep track of incrementation of Rows and Columns
def find_empty_location(arr,l):
    for row in range(9):
        for col in range(9):
            if(arr[row][col]==0):
                l[0]=row
                l[1]=col
                return True
    return False
  
# Returns a boolean which indicates whether any assigned entry
# in the specified row matches the given number.
def used_in_row(arr,row,num):
    for i in range(9):
        if(arr[row][i] == num):
            return True
    return False
  
# Returns a boolean which indicates whether any assigned entry
# in the specified column matches the given number.
def used_in_col(arr,col,num):

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

            # return, if sucess, ya!


            if(solve_sudoku(arr)):
                return True
  
            # failure, unmake & try again
            arr[row][col] = 0
              
    # this triggers backtracking        
    return False 
  
# Driver main function to test above functions
if __name__=="__main__":
      
    # creating a 2D array for the grid
    grid=[[0 for x in range(9)]for y in range(9)]
      
    # assigning values to the grid
    grid=[[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]]
      
    # if sucess print the grid
    if(solve_sudoku(grid)):
        print_grid(grid)
    else:
        print "No solution exists"
  
# The above code has been contributed by Harshit Sidhwa.

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

Sum 2D array in Python using


map() function

Sum 2D array in Python using map() function - GeeksforGeeks


Given a 2-D matrix, we need to find sum of all elements present in matrix ?
Examples:

Input : arr = [[1, 2, 3],


[4, 5, 6],
[2, 1, 2]]
Output : Sum = 26

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.

# Function to calculate sum of all elements in matrix


# sum(arr) is a python inbuilt function which calculates
# sum of each element in a iterable ( array, list etc ).
# map(sum,arr) applies a given function to each item of 
# an iterable and returns a list of the results.
def findSum(arr):
  
    # inner map function applies inbuilt function  
    # sum on each row of matrix arr and returns 
    # list of sum of elements of each row
    return sum(map(sum,arr))  
  
# Driver 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

What does map() do?


The map() function applies a given function to each item of an iterable(list, tuple etc.) and
returns a list of the results. For example see given below example :

# Python code to demonstrate working of map()


  
# Function to calculate square of any number
def calculateSquare(n):
    return n*n
  
# numbers is a list of elements
numbers = [1, 2, 3, 4]
  
# Here map function is mapping calculateSquare 
# function to each element of numbers list.
# It is similar to pass each element of numbers 
# list one by one into calculateSquare function 
# and store result in another list
result = map(calculateSquare, numbers)
  
# resultant output will be [1,4,9,16]
print result

Output :

[1, 4, 9, 16]

Source

https://www.geeksforgeeks.org/sum-2d-array-python-using-map-function/

2123
Chapter 312

Sum of Area of all possible


square inside a rectangle

Sum of Area of all possible square inside a rectangle - GeeksforGeeks


Given two integers L and B denoting the length and breadth of a rectangle respectively. The
task is to calculate the sum of the area of all possible squares that comes into the rectangle.
Examples:

Input: L = 4, B = 3
Output: 54

Input: L = 2, B = 5
Output: 26

The idea is to observe the count of number of squares in a rectangle.

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

So we can deduce that,


Number of squares of size 1*1 will be L*B
Number of squares of size 2*2 will be (L-1)(B-1)

Therefore, the number of squares with size will be:

Number of square of size K = (L-K+1)*(B-K+1)

Therefore, area of total number of squares of size K will be:

Area of total number of square of size K = (L-K+1)*(B-K+1)*K*K

Below is the implementation of above idea:


C++

// CPP program to calculate the sum of area


// of all possible squares that comes
// inside the rectangle
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to calculate the sum of area
// of all possible squares that comes
// inside the rectangle
int calculateAreaSum(int l, int b)
{
    int size = 1;
      
    // Square with max size possible
    int maxSize = min(l,b);
      
    int totalArea = 0;
      
    for(int i=1; i <= maxSize; i++)
    {   
        // calculate total square of a given size
        int totalSquares = (l-size+1)*(b-size+1);
          
        // calculate area of squares of a
        // particular size    
        int area = totalSquares*size*size;
          
        // total area    
        totalArea += area;
           

2126
Chapter 312. Sum of Area of all possible square inside a rectangle

        // increment size    


        size++;
    }
      
    return totalArea;
}
  
// Driver Code
int main()
{
    int l = 4, b = 3;
      
    cout<<calculateAreaSum(l,b);
      
    return 0;
}

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

if __name__ == ”__main__”: l = 4 b = 3 print(calculateAreaSum(l,b)) # This code is


contributed # by ChitraNayal [tabby title=”C#”] // C# program to calculate the // sum
of area of all possible // squares that comes inside // the rectangle using System; 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 totalSquares = (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() { int l = 4, b = 3; Console.Write(calculateAreaSum(l,b)); }
} // This code is contributed // by ChitraNayal [tabby title=”PHP”]
Output:

54

Improved By : ChitraNayal

Source

https://www.geeksforgeeks.org/sum-of-area-of-all-possible-square-inside-a-rectangle/

2128
Chapter 313

Sum of both diagonals of a


spiral odd-order square matrix

Sum of both diagonals of a spiral odd-order square matrix - GeeksforGeeks


We have given a spiral matrix of odd-order, in which we start with the number 1 as center
and moving to the right in a clockwise direction.
Examples :

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:

f(n) = 4[(n^2)] – 6(n-1) + f(n-2)

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;

// as order should be only odd


// we should pass only odd-integers
return (4*n*n - 6*n + 6 + spiralDiaSum(n-2));
}

Below is the implementation.

C++

// C++ program to find sum of


// diagonals of spiral matrix
#include<bits/stdc++.h>
using namespace std;
  
// function returns sum of diagonals
int spiralDiaSum(int n)
{
    if (n == 1)
        return 1;
  
    // as order should be only odd
    // we should pass only odd-integers
    return (4*n*n - 6*n + 6 + spiralDiaSum(n-2));
}
  
// Driver program
int main()
{
    int n = 7;

2130
Chapter 313. Sum of both diagonals of a spiral odd-order square matrix

    cout <<  spiralDiaSum(n);


    return 0;
}

Java

// Java program to find sum of


// diagonals of spiral matrix
  
class GFG 
{
    // function returns sum of diagonals
    static int spiralDiaSum(int n)
    {
        if (n == 1)
            return 1;
      
        // as order should be only odd
        // we should pass only odd-integers
        return (4 * n * n - 6 * n + 6 + 
                     spiralDiaSum(n - 2));
    }
      
    // Driver program to test
    public static void main (String[] args) 
    {
        int n = 7;
        System.out.print(spiralDiaSum(n));
    }
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 program to find sum of


# diagonals of spiral matrix
  
# function returns sum of diagonals
def spiralDiaSum(n):
      
    if n == 1:
        return 1
  
    # as order should be only odd
    # we should pass only odd
    # integers

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#

// C# program to find sum of


// diagonals of spiral matrix
using System;
  
class GFG  {
      
    // function returns sum of diagonals
    static int spiralDiaSum(int n)
    {
        if (n == 1)
            return 1;
      
        // as order should be only odd
        // we should pass only odd-integers
        return (4 * n * n - 6 * n + 6 + 
                spiralDiaSum(n - 2));
    }
      
    // Driver code
    public static void Main (String[] args) 
    {
        int n = 7;
        Console.Write(spiralDiaSum(n));
    }
}
  
// This code is contributed by parashar...

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

function spiralDiaSum( $n)


{
    if ($n == 1)
        return 1;
  
    // as order should be only odd
    // we should pass only odd-integers
    return (4 * $n * $n - 6 * $n + 6 +
                spiralDiaSum($n - 2));
}
  
// Driver Code
$n = 7;
echo spiralDiaSum($n);
  
// This code is contributed by anuj_67.
?>

Output :

261

Improved By : parashar, vt_m

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

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

Method 1 (Brute Force):


Run two loops, one for row and another for column and find integer part of (i / j) and add
to the answer.
Below is the implementation of this approach:

C++

2134
Chapter 314. Sum of matrix element where each elements is integer division of row and
column

// C++ program to find sum of matrix element


// where each element is integer division of
// row and column.
#include<bits/stdc++.h>
using namespace std;
  
// Return sum of matrix element where each element
// is division of its corresponding row and column.
int findSum(int n)
{
    int ans = 0;
    for (int i = 1; i <= n; i++)   // for rows
        for (int j = 1; j <= n; j++) // for columns
            ans += (i/j);
    return ans;
}
  
// Driven Program
int main()
{
    int N = 2;
    cout << findSum(N) << endl;
    return 0;
}

Java

// java program to find sum of matrix


// element where each element is integer
// division of row and column.
  
import java.io.*;
  
class GFG {
      
    // Return sum of matrix element 
    // where each element is division
    // of its corresponding row and
    // column.
    static int findSum(int n)
    {
        int ans = 0;
          
        // for rows
        for (int i = 1; i <= n; i++) 
          
            // for columns
            for (int j = 1; j <= n; j++) 

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#

// C# program to find sum of matrix


// element where each element is integer
// division of row and column.
using System;
  
class GFG {
      
    // Return sum of matrix element 
    // where each element is division
    // of its corresponding row and
    // column.
    static int findSum(int n)
    {
        int ans = 0;
          
        // for rows
        for (int i = 1; i <= n; i++) 
          
            // for columns
            for (int j = 1; j <= n; j++) 
                ans += (i/j);
                  
        return ans;
    }
      
    // Driven Program
    public static void Main () 
    {
        int N = 2;
        Console.WriteLine( findSum(N));
    }

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

Observe, for each jth column


mat[i][k] = 0, for 1 <= k < j, 1 <= i <= N
mat[i][k] = 1, for j <= k < 2*j, 1 <= i <= N
mat[i][k] = 2, for 2*j <= k < 3*j, 1 <= i <= N
and so on.
So, in each column i, there are i – 1 zeroes, followed by i times 1, followed by i times 2 and
so on.
We traverse matrix column by column and sum elements.
Below is the implementation of this approach
:

C++

// C++ program to find sum of matrix element


// where each element is integer divison of
// row and column.
#include<bits/stdc++.h>
using namespace std;
  
// Return sum of matrix element where each
// element is division of its corresponding

2138
Chapter 314. Sum of matrix element where each elements is integer division of row and
column

// row and column.


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
int main()
{
    int N = 2;
    cout << findSum(N) << endl;
    return 0;
}

Java

// java program to find sum of matrix element


// where each element is integer divison of
// row and column.
  
import java.io.*;
  
class GFG {

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#

// C# program to find sum of matrix 

2140
Chapter 314. Sum of matrix element where each elements is integer division of row and
column

// element where each element is 


// integer divison of row and column.
using System;
  
class GFG 
{
      
    // 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;
    }
      
    // Driver Code
    public static void Main () 
    {
        int N = 2;
        Console.WriteLine(findSum(N));
    }

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

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.

Method 1 (Brute Force):


Simply construct a matrix of n rows and n columns and initialize each cell with absolute

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++

// C++ program to find sum of matrix in which each


// element is absolute difference of its corresponding
// row and column number row.
#include<bits/stdc++.h>
using namespace std;
  
// Retuen the sum of matrix in which each element
// is absolute difference of its corresponding row
// and column number row
int findSum(int n)
{
    // Generate matrix
    int arr[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            arr[i][j] = 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;
}
  
// Driven Program
int main()
{
    int n = 3;
    cout << findSum(n) << endl;
    return 0;
}

Java

// Java program to find sum of matrix


// in which each element is absolute
// difference of its corresponding
// row and column number row.

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#

// C# program to find sum of matrix


// in which each element is absolute
// difference of its corresponding
// row and column number row.
using System;
  
public class GFG {
  
// Retuen the sum of matrix in which
// each element is absolute difference

2146
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers

// 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;
        Console.WriteLine(findSum(n));
    }
}
  
// This code is contributed by vt_m.

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++

// C++ program to find sum of matrix in which


// each element is absolute difference of its
// corresponding row and column number row.
#include<bits/stdc++.h>
using namespace std;
  

2148
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers

// Retuen the sum of matrix in which each


// element is absolute difference of its
// corresponding row and column number row
int findSum(int n)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += i*(n-i);
    return 2*sum;
}
  
// Driven Program
int main()
{
    int n = 3;
    cout << findSum(n) << endl;
    return 0;
}

Java

// Java program to find sum of matrix in which


// each element is absolute difference of its
// corresponding row and column number row.
import java.io.*;
  
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)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += i * (n - i);
    return 2 * sum;
}
  
    // Driver Code
    static public void main(String[] args)
    {
        int n = 3;
        System.out.println(findSum(n));
    }
}
  
// This code is contributed by vt_m.

2149
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers

C#

// C# program to find sum of matrix in which


// each element is absolute difference of its
// corresponding row and column number row.
using System;
  
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)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += i * (n - i);
    return 2 * sum;
}
  
    // Driver Code
    static public void Main(String[] args)
    {
        int n = 3;
        Console.WriteLine(findSum(n));
    }
}
  
// This code is contributed by vt_m.

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.

Sum of first n natural number = ((n)*(n + 1))/2.


Sum of first n natural number = ((n)*(n + 1)*(2*n + 1)/6.

Below is the implementation of above idea :

C++

// C++ program to find sum of matrix in which


// each element is absolute difference of its
// corresponding row and column number row.
#include<bits/stdc++.h>
using namespace std;
  
// Retuen the sum of matrix in which each element
// is absolute difference of its corresponding
// row and column number row
int findSum(int n)
{
    n--;
    int sum = 0;

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

// Java program to find sum of matrix in which


// each element is absolute difference of its
// corresponding row and column number row.
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)
{
    n--;
    int sum = 0;
    sum += (n * (n + 1)) / 2;
    sum += (n * (n + 1) * (2 * n + 1)) / 6;
    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#

// C# program to find sum of matrix in which

2152
Chapter 315. Sum of matrix in which each element is absolute difference of its row and
column numbers

// each element is absolute difference of its


// corresponding row and column number row.
using System;
  
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)
{
    n--;
    int sum = 0;
    sum += (n * (n + 1)) / 2;
    sum += (n * (n + 1) * (2 * n + 1)) / 6;
    return sum;
}
  
    // Driver Code
    static public void Main(String[] args)
    {
        int n = 3;
        Console.WriteLine(findSum(n));
    }
}
  
// This code is contributed by vt_m.

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

Sum of middle row and column


in Matrix

Sum of middle row and column in Matrix - GeeksforGeeks


Given a integer matrix of odd dimensions (3 * 3, 5 * 5). then the task is to find the sum of
the middle row & column elements.
Examples:

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

// C++ program to find sum of 


// middle row and column in matrix
#include <iostream>
using namespace std;
const int MAX = 100;

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

// java  program to find sum of 


// middle row and column in matrix
  
import java.io.*;
  
class GFG {
      
  
static  int MAX = 100;
  
 static void middlesum(int mat[][], int n)
{
  

2156
Chapter 316. Sum of middle row and column in Matrix

    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];
      
    System.out.println ( "Sum of middle row = "
                  + row_sum);
      
    // loop for sum of column
    for (int i = 0; i < n; i++)
        col_sum += mat[i][n / 2];
      
    System.out.println ( "Sum of middle column = "
                 + col_sum);
}
  
// Driver function
    public static void main (String[] args) {
        int mat[][] = {{2, 5, 7},
                    {3, 7, 2}, 
                    {5, 6, 9}};
      
        middlesum(mat, 3);
      
    }
}
  
// This code is contributed by vt_m.

Python3

# Python program to find sum of 


# middle row and column in matrix
  
   
def middlesum(mat,n):
   
    row_sum = 0
    col_sum = 0
       
    # loop for sum of row
    for i in range(n):
        row_sum += mat[n // 2][i]
       
    print("Sum of middle row = ",
                     row_sum)
       

2157
Chapter 316. Sum of middle row and column in Matrix

    # loop for sum of column


    for i in range(n):
        col_sum += mat[i][n // 2]
       
    print("Sum of middle column = ",
                            col_sum)
  
# Driver code
mat= [[2, 5, 7],
     [3, 7, 2], 
     [5, 6, 9]]
       
middlesum(mat, 3)
  
# This code is contributed
# by Anant Agarwal.

C#

// C# program to find sum of 


// middle row and column in matrix
using System;
  
class GFG {
      
  
    //static int MAX = 100;
      
    static void middlesum(int [,]mat, 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];
          
        Console.WriteLine ( "Sum of middle row = "
                    + row_sum);
          
        // loop for sum of column
        for (int i = 0; i < n; i++)
            col_sum += mat[i, n / 2];
          
        Console.WriteLine ( "Sum of middle column = "
                            + col_sum);
    }
  

2158
Chapter 316. Sum of middle row and column in Matrix

    // Driver function


    public static void Main () {
        int [,]mat = {{2, 5, 7},
                    {3, 7, 2}, 
                    {5, 6, 9}};
      
        middlesum(mat, 3);
      
    }
}
  
// This code is contributed by vt_m.

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:

Sum of middle row = 12


Sum of middle column = 18

Time Complexity: O(n)


Improved By : vt_m

Source

https://www.geeksforgeeks.org/sum-middle-row-column-matrix/

2160
Chapter 317

Sum of upper triangle and lower


triangle

Sum of upper triangle and lower triangle - GeeksforGeeks


Given a matrix print the sum of upper and lower triangular elements (i.e elements on
diagonal and the upper and lower elements).
Examples :

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++

// C++ program to calculate the sum 


// of upper and lower triangle
#include <bits/stdc++.h>
using namespace std;
  
/*function to calculate sum*/
void sum(int mat[3][3], int r, int 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

// Java program to calculate the sum 


// of upper and lower triangle
  
class GFG
{

2162
Chapter 317. Sum of upper triangle and lower triangle

    /*function to calculate sum*/


    static void sum(int mat[][], int r, int c)
    {
        int i, j;
        int upper_sum = 0;
        int lower_sum = 0;
          
        /*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];
                }
            }
      
        System.out.println("Upper sum is " + upper_sum);
          
        /*calculate sum of lower*/
        for (i = 0; i < r; i++)
            for (j = 0; j < c; j++) 
            {
                if (j <= i) 
                {
                    lower_sum += mat[i][j];
                }
            }
      
        System.out.print("Lower sum is " + lower_sum);
    } 
          
    // Driver code
    public static void main (String[] args)
    {
        int r = 3;
        int c = 3;
      
        /*giving the matrix*/
        int mat[][] = {{ 6, 5, 4 },
                        { 1, 2, 5 },
                        { 7, 9, 7 }};
                          
        /*calling the function*/
        sum(mat, r, c);
    }
}
  

2163
Chapter 317. Sum of upper triangle and lower triangle

// This code is contributed by Anant Agarwal.

C#

// C# program to calculate the sum 


// of upper and lower triangle
using System;
  
class GFG
{
    /*function to calculate sum*/
    static void sum(int [,]mat, int r, int c)
    {
        int i, j;
        int upper_sum = 0;
        int lower_sum = 0;
          
        /*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];
                }
            }
      
        Console.WriteLine("Upper sum is " + 
                                upper_sum);
          
        /*calculate sum of lower*/
        for (i = 0; i < r; i++)
            for (j = 0; j < c; j++) 
            {
                if (j <= i) 
                {
                   lower_sum += mat[i,j];
                }
            }
      
        Console.Write("Lower sum is " + 
                            lower_sum);
    } 
          
    // Driver code
    public static void Main ()
    {
        int r = 3;

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

Improved By : nitin mittal, Sam007

Source

https://www.geeksforgeeks.org/sum-upper-triangle-lower-triangle/

2166
Chapter 318

Summed Area Table –


Submatrix Summation

Summed Area Table - Submatrix Summation - GeeksforGeeks


Given a matrix of size M x N, there are large number of queries to find submatrix sums.
Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find
out.
How to preprocess the matrix so that submatrix sum queries can be performed in O(1) time.
Example:

tli : Row number of top left of query submatrix


tlj : Column number of top left of query submatrix
rbi : Row number of bottom right of query submatrix
rbj : Column number of bottom right of query submatrix

Input: mat[M][N] = {{1, 2, 3, 4, 6},


{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
Query1: tli = 0, tlj = 0, rbi = 1, rbj = 1
Query2: tli = 2, tlj = 2, rbi = 3, rbj = 4
Query3: tli = 1, tlj = 2, rbi = 3, rbj = 3;

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.

// Pseudo code of Naive algorithm.


Arr[][] = input_matrix
For each query:
Input tli, tlj, rbi, rbj
sum = 0
for i from tli to tbi (inclusive):
for j from tlj to rbj(inclusive):
sum += Arr[i][j]
print(sum)

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 :

The optimized solution is implemented in below post.


Implementation of optimized approach

Source

https://www.geeksforgeeks.org/summed-area-table-submatrix-summation/

2168
Chapter 319

Swap major and minor


diagonals of a square matrix

Swap major and minor diagonals of a square matrix - GeeksforGeeks


Given a square matrix, swap the element of major and minor diagonals.

Major Diagonal Elements of a Matrix :


The Major Diagonal Elements are the ones that occur from Top Left of Matrix
Down To Bottom Right Corner. The Major Diagonal is also known as Main
Diagonal or Primary Diagonal.
Minor Diagonal Elements of a Matrix :
The Minor Diagonal Elements are the ones that occur from Top Right of Matrix
Down To Bottom Left Corner. Also known as Secondary Diagonal.

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

Below is the implementation of above approach :

C++

// CPP Program to swap diagonal of a matrix


#include <bits/stdc++.h>
using namespace std;
  
// size of square matrix
#define N 3
  
// Function to swap diagonal of matrix
void swapDiagonal(int matrix[][N]) {
  for (int i = 0; i < N; i++)
    swap(matrix[i][i], matrix[i][N - i - 1]);
}
  
// Driver Code
int main() {
  int matrix[N][N] = {{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++)
      cout << matrix[i][j] << " ";
    cout << endl;
  }
  
  return 0;
}

Java

// Java implementation to swap


// diagonal of a matrix
import java.io.*;
  
class Gfg {
static int N = 3;
  
// Function to swap diagonal of matrix
static void swapDiagonal(int matrix[][]) {
    for (int i = 0; i < N; i++) {

2170
Chapter 319. Swap major and minor diagonals of a square matrix

    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(String arg[]) {
    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++)
        System.out.print(matrix[i][j] + " ");
    System.out.println();
    }
}
}
  
// This code is contributed by Anant Agarwal.

Python3

# Python3 Program to swap diagonal of a matrix


  
# size of square matrix
N = 3
  
# Function to swap diagonal of matrix
def swapDiagonal(matrix):
      
    for i in range(N):
          
        matrix[i][i], matrix[i][N-i-1] = \
            matrix[i][N-i-1], matrix[i][i]
  
  
# Driver Code
matrix = [[0, 1, 2],
          [3, 4, 5],
          [6, 7, 8]]
  
# swap diagonals of matrix
swapDiagonal(matrix);

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

// PHP Program to swap 


// diagonal of a matrix
  
// size of square matrix
$N = 3;
  
// Function to swap 
// diagonal of matrix
function swapDiagonal($matrix) 
{
    global $N;
    for ($i = 0; $i < $N; $i++)
    {
        $tmp=$matrix[$i][$i];
        $matrix[$i][$i] = $matrix[$i][$N - $i - 1];
        $matrix[$i][$N - $i - 1] = $tmp;
    }
      
// Displaying modified matrix
for ($i = 0; $i < $N; $i++) 
{
    for ($j = 0; $j < $N; $j++)
        echo $matrix[$i][$j] . " ";
    echo "\n";
}
}
  
// Driver Code
$matrix = array(array(0, 1, 2), 
                array(3, 4, 5), 
                array(6, 7, 8));
  
swapDiagonal($matrix);
  
// This code is contributed by mits
?>

Output :

2 1 0
3 4 5
8 7 6

Improved By : Mithun Kumar

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

System of Linear Equations in


three variables using Cramer’s
Rule

System of Linear Equations in three variables using Cramer’s Rule - GeeksforGeeks


Cramer’s rule : In linear algebra, Cramer’s rule is an explicit formula for the solution
of a system of linear equations with as many equations as unknown variables. It expresses
the solution in terms of the determinants of the coefficient matrix and of matrices obtained
from it by replacing one column by the column vector of right-hand-sides of the equations.
Cramer’s rule is computationally inefficient for systems of more than two or three equations.
Suppose we have to solve these equations:
a1 x + b1 y + c1 z = d1
a2 x + b2 y + c2 z = d2
a3 x + b3 y + c3 z = d3
Following the Cramer’s Rule, first find the determinant values of all four matrices.

2175
Chapter 320. System of Linear Equations in three variables using Cramer’s Rule

There are 2 cases:


Case I : When D � 0 In this case we have,
x = D1/D
y = D2/D
z = D3/D
Hence unique value of x, y, z will be obtained.
Case II : When D = 0
(a) When at least one of D1, D2 and D3 is non zero: Then no solution is
possible and hence system of equations will be inconsistent.
(b) When D = 0 and D1 = D2 = D3 = 0: Then the system of equations will
be consistent and it will have infinitely many solutions.

Example

Consider the following system of linear equations.


[2x – y + 3z = 9], [x + y + z = 6], [x – y + z = 2]

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]

Below is the implementation in C++/

// CPP program to calculate solutions of linear


// equations using cramer's rule
#include <bits/stdc++.h>
using namespace std;
  
// This functions finds the determinant of Matrix
double determinantOfMatrix(double mat[3][3])
{
    double ans;
    ans = mat[0][0] * (mat[1][1] * mat[2][2] - mat[2][1] * mat[1][2])
          - mat[0][1] * (mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0])
          + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]);
    return ans;
}
  
// This function finds the solution of system of
// linear equations using cramer's rule
void findSolution(double coeff[3][4])
{
    // Matrix d using coeff as given in cramer's rule
    double d[3][3] = {
        { coeff[0][0], coeff[0][1], coeff[0][2] },
        { coeff[1][0], coeff[1][1], coeff[1][2] },
        { coeff[2][0], coeff[2][1], coeff[2][2] },
    };
    // Matrix d1 using coeff as given in cramer's rule
    double d1[3][3] = {
        { coeff[0][3], coeff[0][1], coeff[0][2] },
        { coeff[1][3], coeff[1][1], coeff[1][2] },
        { coeff[2][3], coeff[2][1], coeff[2][2] },
    };
    // Matrix d2 using coeff as given in cramer's rule
    double d2[3][3] = {
        { coeff[0][0], coeff[0][3], coeff[0][2] },
        { coeff[1][0], coeff[1][3], coeff[1][2] },
        { coeff[2][0], coeff[2][3], coeff[2][2] },
    };

2177
Chapter 320. System of Linear Equations in three variables using Cramer’s Rule

    // Matrix d3 using coeff as given in cramer's rule


    double d3[3][3] = {
        { coeff[0][0], coeff[0][1], coeff[0][3] },
        { coeff[1][0], coeff[1][1], coeff[1][3] },
        { coeff[2][0], coeff[2][1], coeff[2][3] },
    };
  
    // Calculating Determinant of Matrices d, d1, d2, d3
    double D = determinantOfMatrix(d);
    double D1 = determinantOfMatrix(d1);
    double D2 = determinantOfMatrix(d2);
    double D3 = determinantOfMatrix(d3);
    printf("D is : %lf \n", D);
    printf("D1 is : %lf \n", D1);
    printf("D2 is : %lf \n", D2);
    printf("D3 is : %lf \n", D3);
  
    // Case 1
    if (D != 0) {
        // Coeff have a unique solution. Apply Cramer's Rule
        double x = D1 / D;
        double y = D2 / D;
        double z = D3 / D; // calculating z using cramer's rule
        printf("Value of x is : %lf\n", x);
        printf("Value of y is : %lf\n", y);
        printf("Value of z is : %lf\n", z);
    }
    // Case 2
    else {
        if (D1 == 0 && D2 == 0 && D3 == 0)
            printf("Infinite solutions\n");
        else if (D1 != 0 || D2 != 0 || D3 != 0)
            printf("No solutions\n");
    }
}
  
// Driver Code
int main()
{
  
    // storing coefficients of linear equations in coeff matrix
    double coeff[3][4] = {
        { 2, -1, 3, 9 },
        { 1, 1, 1, 6 },
        { 1, -1, 1, 2 },
    };
  
    findSolution(coeff);

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

The Celebrity Problem

The Celebrity Problem - GeeksforGeeks


In a party of N people, only one person is known to everyone. Such a person may be
present in the party, if yes, (s)he doesn’t know anyone in the party. We can only ask
questions like “does A know B? “. Find the stranger (celebrity) in minimum number of
questions.
We can describe the problem input as an array of numbers/characters representing persons
in the party. We also have a hypothetical function HaveAcquaintance(A, B) which returns
true if A knows B, false otherwise. How can we solve the problem.
We measure the complexity in terms of calls made to HaveAcquaintance().
Method 1 (Graph)
We can model the solution using graphs. Initialize indegree and outdegree of every vertex
as 0. If A knows B, draw a directed edge from A to B, increase indegree of B and outdegree
of A by 1. Construct all possible edges of the graph for every possible pair [i, j]. We have
NC2 pairs. If celebrity is present in the party, we will have one sink node in the graph with
outdegree of zero, and indegree of N-1. We can find the sink node in (N) time, but the
overall complexity is O(N2 ) as we need to construct the graph first.
Method 2 (Recursion)
We can decompose the problem into combination of smaller instances. Say, if we know
celebrity of N-1 persons, can we extend the solution to N? We have two possibilities,
Celebrity(N-1) may know N, or N already knew Celebrity(N-1). In the former case, N
will be celebrity if N doesn’t know anyone else. In the later case we need to check that
Celebrity(N-1) doesn’t know N.
Solve the problem of smaller instance during divide step. On the way back, we find the
celebrity (if present) from the smaller instance. During combine stage, check whether the
returned celebrity is known to everyone and he doesn’t know anyone. The recurrence of the
recursive decomposition is,
T(N) = T(N-1) + O(N)

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).

• If A knows B, then A can’t be celebrity. Discard A, and B may be celebrity.


• If A doesn’t know B, then B can’t be celebrity. Discard B, and A may be celebrity.
• Repeat above two steps till we left with only one person.
• Ensure the remained person is celebrity. (Why do we need this step?)

We can use stack to verity celebrity.

1. Push all the celebrities into a stack.


2. Pop off top two persons from the stack, discard one person based on return status of
HaveAcquaintance(A, B).
3. Push the remained person onto stack.
4. Repeat step 2 and 3 until only one person remains in the stack.
5. Check the remained person in stack doesn’t have acquaintance with anyone else.

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++

// C++ program to find celebrity


#include <bits/stdc++.h>
#include <list>
using namespace std;
  
// Max # of persons in the party
#define N 8
  
// Person with 2 is celebrity
bool MATRIX[N][N] = {{0, 0, 1, 0},
                    {0, 0, 1, 0},
                    {0, 0, 0, 0},
                    {0, 0, 1, 0}};
  
bool knows(int a, int b)
{
    return MATRIX[a][b];
}
  

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

// Java program to find celebrity using


// stack data structure
  
import java.util.Stack;
  
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 boolean knows(int a, int b) 
    {
        boolean res = (MATRIX[a][b] == 1) ? 

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

            //  know 'c' or 'a' doesn't 


            // know any person, return -1
            if (i != c && (knows(c, i) || 
                          !knows(i, c)))
                return -1;
        }
        return c;
    }
  
    // 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

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++

// C++ program to find 


// celebrity in O(n) time
// and O(1) extra space
#include <bits/stdc++.h>
using namespace std;
  
// Max # of persons in the party
#define N 8
  
// Person with 2 is celebrity
bool MATRIX[N][N] = {{0, 0, 1, 0},
                     {0, 0, 1, 0},
                     {0, 0, 0, 0},
                     {0, 0, 1, 0}
};
  
bool knows(int a, int b)
{
    return MATRIX[a][b];
}
  
// Returns id of celebrity
int findCelebrity(int n)
{
    // Initialize two pointers 
    // as two corners
    int a = 0;
    int b = n - 1;
  

2186
Chapter 321. The Celebrity Problem

    // 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;
}
  
// Driver code
int main()
{
    int n = 4;
    int id = findCelebrity(n);
    id == -1 ? cout << "No celebrity" :
               cout << "Celebrity ID " 
                    << id;
    return 0;
}

Java

// Java program to find 


// celebrity using two 
// pointers
  
class GFG 
{
    // Person with 2 is celebrity
    static int MATRIX[][] = { { 0, 0, 1, 0 },

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

        // 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;
    }
  
    // Driver Code
    public static void Main() 
    {
        int n = 4;
        int result = findCelebrity(n);
        if (result == -1) 
        {
            Console.WriteLine("No Celebrity");
        } 
        else
            Console.WriteLine("Celebrity ID " + 
                                       result);
    }
}
  
// This code is contributed by anuj_67.

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

                (knows($a, $i) || 


                !knows($i, $a)) )
            return -1;
    }
  
    return $a;
}
  
// Driver code
$n = 4;
$id = findCelebrity($n);
if($id == -1)
echo "No celebrity" ;
else
echo "Celebrity ID " , $id;
  
// This code is contributed by anuj_67.
?>

Output :

Celebrity ID 2

Thanks to Sissi Peng for suggesting this method.


Related Article:
Number of sink nodes in a graph
Exercises:
1. Write code to find celebrity. Don’t use any data structures like graphs, stack, etc… you
have access to N and HaveAcquaintance(int, int) only.
2. Implement the algorithm using Queues. What is your observation? Compare your solu-
tion with Finding Maximum and Minimum in an array and Tournament Tree. What are
minimum number of comparisons do we need (optimal number of calls to HaveAcquain-
tance())?
— Venki. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
Improved By : vt_m

Source

https://www.geeksforgeeks.org/the-celebrity-problem/

2192
Chapter 322

Total coverage of all zeros in a


binary matrix

Total coverage of all zeros in a binary matrix - GeeksforGeeks


Given a binary matrix that is, it contains 0s and 1s only, we need to find sum of coverage of
all zeros of the matrix where coverage for a particular 0 is defined as total number of ones
around a zero in left, right, up and bottom directions. The ones can be anywhere till corner
point in a direction.
Examples:

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++

//  C++ program to get total coverage of all zeros in


// a binary matrix
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
  
// Returns total coverage of all zeros in mat[][]
int getTotalCoverageOfMatrix(int mat[R][C])
{
    int res = 0;
  
    //  looping for all rows of matrix
    for (int i = 0; i < R; i++)
    {
        bool isOne = false;  // 1 is not seen yet
  
        // looping in columns from left to right
        // direction to get left ones
        for (int j = 0; j < C; j++)
        {
            // If one is found from left
            if (mat[i][j] == 1)

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

    int mat[R][C] = {{0, 0, 0, 0},


        {1, 0, 0, 1},
        {0, 1, 1, 0},
        {0, 1, 0, 0}
    };
  
    cout << getTotalCoverageOfMatrix(mat);
  
    return 0;
}

Java

// Java program to get total 


// coverage of all zeros in 
// a binary matrix
import java .io.*;
  
class GFG 
{
static int R = 4;
static int C = 4;
  
// Returns total coverage
// of all zeros in mat[][]
static int getTotalCoverageOfMatrix(int [][]mat)
{
    int res = 0;
  
    // looping for all 
    // rows of matrix
    for (int i = 0; i < R; i++)
    {
        // 1 is not seen yet
        boolean isOne = false; 
  
        // looping in columns from 
        // left to right direction
        // to get left ones
        for (int j = 0; j < C; j++)
        {
            // If one is found
            // from left
            if (mat[i][j] == 1)
                isOne = true;
  
            // If 0 is found and we 
            // have found a 1 before.

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#

// C# program to get total coverage 


// of all zeros in a binary matrix
using System;
  
class GFG {
      
static int R = 4;
static int C = 4;
  
// Returns total coverage of all zeros in mat[][]
static int getTotalCoverageOfMatrix(int [,]mat)
{
    int res = 0;
  
    // looping for all rows of matrix
    for (int i = 0; i < R; i++)
    {
        // 1 is not seen yet
        bool isOne = false; 
  
        // looping in columns from left to 
        // right direction to get left ones
        for (int j = 0; j < C; j++)
        {
            // If one is found from left
            if (mat[i,j] == 1)
                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.

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

// This code is contributed by vt_m.

Output:

20

Time Complexity: O(n2 )


Auxiliary Space: O(1)
Improved By : vt_m

Source

https://www.geeksforgeeks.org/total-coverage-zeros-binary-matrix/

2200
Chapter 323

Total number of decreasing


paths in a matrix

Total number of decreasing paths in a matrix - GeeksforGeeks


Given a matrix of size N X N of integers. The task is to find the number of decreasing
path in the matrix. You are allowed to start from any cell and from the cell (i, j), you are
allowed to move to (i + 1, j), (i – 1, j), (i, j + 1) and (i, j – 1) cell.
Examples:

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++

// CPP program to count number


// of decreasing path in a matrix
#include <bits/stdc++.h>
using namespace std;
#define MAX 100
  
// Function that returns the number of
// decreasing paths from a cell(i, j)
int CountDecreasingPathsCell(int mat[MAX][MAX], int dp[MAX][MAX], 
                                              int n, int x, int y)
{
    // checkinf if already calculated
    if (dp[x][y] != -1)
        return dp[x][y];
  
    // all possible paths
    int delta[4][2] = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
    int newx, newy;
  
    // counts the total number of paths
    int ans = 1;
  
    // In all four allowed direction.
    for (int i = 0; i < 4; i++) {
  
        // new co-ordinates
        newx = x + delta[i][0];
        newy = y + delta[i][1];
  
        // Checking if not going out of matrix and next
        // cell value is less than current cell value.
        if (newx >= 0 && newx < n && newy >= 0
            && newy < n && mat[newx][newy] < mat[x][y]) {
            ans += CountDecreasingPathsCell(mat, dp, n, newx, newy);
        }
    }
    // fucntion that returns the answer
    return dp[x][y] = ans;
}
  

2202
Chapter 323. Total number of decreasing paths in a matrix

// Function that counts the total


// decreasing path in the matrix
int countDecreasingPathsMatrix(int n,
                               int mat[MAX][MAX])
{
    int dp[MAX][MAX];
  
    // 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
int main()
{
    int n = 2;
  
    int mat[MAX][MAX] = { { 1, 2 }, { 1, 3 } };
    // function call that returns the
    // count of decreasing paths in a matrix
    cout << countDecreasingPathsMatrix(n, mat)
         << endl;
    return 0;
}

Java

// Java program to count number


// of decreasing path in a matrix
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{
public static Scanner scn = 
      new Scanner(System.in);
  

2203
Chapter 323. Total number of decreasing paths in a matrix

// Function that returns the number of


// decreasing paths from a cell(i, j)
public static int CountDecreasingPathsCell(int mat[][], int dp[][], 
                                           int n, int x, int y)
    {
        // checkinf if already calculated
        if (dp[x][y] != -1)
            return dp[x][y];
      
        // all possible paths
        int delta[][] = { { 0, 1 }, { 1, 0 }, 
                          { -1, 0}, { 0, -1}};
        int newx, newy;
      
        // counts the total
        // number of paths
        int ans = 1;
      
        // In all four allowed direction.
        for (int i = 0; i < 4; i++) 
        {
      
            // new co-ordinates
            newx = x + delta[i][0];
            newy = y + delta[i][1];
      
            // Checking if not going out 
            // of matrix and next cell 
            // value is less than current 
            // cell value.
            if (newx >= 0 && newx < n && newy >= 0 && 
                newy < n && mat[newx][newy] < mat[x][y]) 
            {
                ans += CountDecreasingPathsCell(mat, dp, n, 
                                                newx, newy);
            }
        }
          
        // fucntion that 
        // returns the answer
        return dp[x][y] = ans;
    }
      
// Function that counts the total
// decreasing path in the matrix
public static int countDecreasingPathsMatrix(int n, 
                                             int mat[][])
    {

2204
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
public static void main(String[] args) 
{
    int n = 2;
          
    int mat[][]= {{1, 2}, 
                  {1, 3}};
      
    // function call that returns the
    // count of decreasing paths in a matrix
    System.out.println(countDecreasingPathsMatrix(n, mat));
  

}
  
// This code is contributed by khyati grover

C#

// C# program to count number


// of decreasing path in a matrix
using System;
  
class GFG
{
      
// Function that returns 
// the number of decreasing 
// paths from a cell(i, j)

2205
Chapter 323. Total number of decreasing paths in a matrix

public static int CountDecreasingPathsCell(int[,] mat, int[,] dp, 


                                           int n, int x, int y)
{
    // checkinf if already 
    // calculated
    if (dp[x, y] != -1)
        return dp[x, y];
  
    // all possible paths
    int[,] delta = {{0, 1}, {1, 0}, 
                    {-1, 0},{0, -1}};
    int newx, newy;
  
    // counts the total
    // number of paths
    int ans = 1;
  
    // In all four 
    // allowed direction.
    for (int i = 0; i < 4; i++) 
    {
  
        // new co-ordinates
        newx = x + delta[i,0];
        newy = y + delta[i,1];
  
        // Checking if not going out 
        // of matrix and next cell 
        // value is less than current 
        // cell value.
        if (newx >= 0 && newx < n && 
            newy >= 0 && newy < n && 
            mat[newx,newy] < mat[x,y]) 
        {
            ans += CountDecreasingPathsCell(mat, dp, n, 
                                            newx, newy);
        }
    }
      
    // fucntion that 
    // returns the answer
    return dp[x,y] = ans;
}
  
// Function that counts the total
// decreasing path in the matrix
public static int countDecreasingPathsMatrix(int n, 
                                        int[,] mat)

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:

Time Complexity : O(N2 )


Auxiliary Space : O(N2 )
Improved By : khyatigrover, Mahadev99

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

Turn an image by 90 degree

Turn an image by 90 degree - GeeksforGeeks


Given an image, how will you turn it by 90 degrees? A vague question. Minimize the browser
and try your solution before going further.
An image can be treated as 2D matrix which can be stored in a buffer. We are provided
with matrix dimensions and it’s base address. How can we turn it?
For example see the below picture,

* * * ^ * * *
* * * | * * *
* * * | * * *
* * * | * * *

After rotating right, it appears (observe arrow direction)

* * * *
* * * *
* * * *
-- - - >
* * * *
* * * *
* * * *

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

first row of source ------> last column of destination


second row of source ------> last but-one column of destination
so ... on
last row of source ------> first column of destination

2209
Chapter 324. Turn an image by 90 degree

In pictorial form, we can represent the above transformations of an (m x n) matrix into (n


x m) matrix,

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)

for (r = 0; r < m; r++)


{
   for (c = 0; c < n; c++)
   {
      // Hint: Map each source element indices into
// indices of destination matrix element.
       dest_buffer [ c ] [ m - r - 1 ] = source_buffer [ r ] [ c ];
   }
}

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:

// C program to turn an 


// image by 90 Degree
#include <stdio.h>
#include <stdlib.h>
  

2210
Chapter 324. Turn an image by 90 degree

void displayMatrix(unsigned int const *p, 


                   unsigned int row, 
                   unsigned int col);
                     
void rotate(unsigned int *pS, 
            unsigned int *pD, 
            unsigned int row, 
            unsigned int col);
              
void displayMatrix(unsigned int const *p, 
                   unsigned int r, 
                   unsigned int c) 
{
    unsigned int row, col;
    printf("\n\n");
  
    for (row = 0; row < r; row++)
    {
        for (col = 0; col < c; col++)
            printf("%d\t", * (p + row * c + col));
        printf("\n");
    }
  
    printf("\n\n");
}
  
void rotate(unsigned int *pS, 
            unsigned int *pD,
            unsigned int row, 
            unsigned int col)
{
    unsigned int r, c;
    for (r = 0; r < row; r++)
    {
        for (c = 0; c < col; c++)
        {
            *(pD + c * row + (row - r - 1)) = 
                            *(pS + r * col + c);
        }
    }
}
  
// Driver Code
int main()
{
      
    // declarations
    unsigned int image[][4] = {{1,2,3,4}, 

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

Inplace rotate square matrix by 90 degrees

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

Unique cells in a binary matrix

Unique cells in a binary matrix - GeeksforGeeks


Given a matrix of size n x m consisting of 0’s and 1’s.We need to find number of unique cells
with value 1 such that corresponding entire row and entire column does not have another
1.Return the number of unique cells.
Examples:

Input : mat[][] = {0, 1, 0, 0


0, 0, 1, 0
1, 0, 0, 1}
Answer : 2
The two 1s that are unique
in their rows and columns
are highlighted.

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

Method 1- Brute Force Approach


In this approach, we are going to check for each cell with value 1 whether the corresponding
rows
satisfy our requirement. We will check in corresponding rows and columns of each cell with
value 1.
C++

2214
Chapter 325. Unique cells in a binary matrix

// C++ program to count unique cells in 


// a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
  
// Returns true if mat[i][j] is unique
bool isUnique(int mat[][MAX], int i, int j, 
                              int n, int m)
{
    // checking in row calculating sumrow
    // will be moving  column wise
    int sumrow = 0;
    for (int k = 0; k < m; k++) {
        sumrow += mat[i][k];
        if (sumrow > 1)
           return false; 
    }
  
    // checking in column calculating sumcol
    // will be moving  row wise
    int sumcol = 0;
    for (int k = 0; k < n; k++) {
        sumcol += mat[k][j];
        if (sumcol > 1)
            return false; 
    }
  
    return true;
}
  
int countUnique(int mat[][MAX], int n, int m)
{
    int uniquecount = 0;
    for (int i = 0; i < n; i++) 
        for (int j = 0; j < m; j++) 
            if (mat[i][j] && 
             isUnique(mat, i, j, n, m))
                    uniquecount++;
    return uniquecount;
}
  
// Driver code
int main()
{
    int mat[][MAX] = {{0, 1, 0, 0},
                   {0, 0, 1, 0},
                   {1, 0, 0, 1}};

2215
Chapter 325. Unique cells in a binary matrix

    cout << countUnique(mat, 3, 4);


    return 0;
}

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:

Time Complexity: O((n*m)*(n+m))


This goes to order of cubic due to check condition for every corresponding row and column
Method 2- O(n*m) Approach
In this approach, we are going to use extra space for rowsum array and colsum array and
then check for each cell with value 1 whether the corresponding rowsum array and colsum
array values are 1.
C++

// Efficient C++ program to count unique


// cells in a binary matrix
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
int countUnique(int mat[][MAX], int n, int m)
{
    int rowsum[n], colsum[m];
    memset(colsum, 0, sizeof(colsum));
    memset(colsum, 0, sizeof(colsum));
  
    // Count number of 1s in each row
    // and in each column
    for (int i = 0; i < n; i++) 
        for (int j = 0; j < m; j++) 
            if (mat[i][j]) {
                rowsum[i]++;

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:

Time Complexity – O(n*m)


Auxiliary Space – O(n+m)
Improved By : jit_t

Source

https://www.geeksforgeeks.org/unique-cells-binary-matrix/

2218
Chapter 326

Unique paths in a Grid with


Obstacles

Unique paths in a Grid with Obstacles - GeeksforGeeks


Given a grid of size m * n, let us assume you are starting at (1, 1) and your goal is to reach
(m, n). At any instance, if you are on (x, y), you can either go to (x, y + 1) or (x + 1, y).
Now consider if some obstacles are added to the grids. How many unique paths would there
be?
An obstacle and empty space are marked as 1 and 0 respectively in the grid.
Examples:

Input: [[0, 0, 0],


[0, 1, 0],
[0, 0, 0]]
Output : 2
There is only one obstacle in the middle.

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

# Python code to find number of unique paths in a 


# matrix with obstacles.
  
def uniquePathsWithObstacles(A):
    
    # create a 2D-matrix and initializing with value 0
    paths = [[0]*len(A[0]) for i in A]
      
    # initializing the left corner if no obstacle there
    if A[0][0] == 0:
        paths[0][0] = 1
      
    # initializing first column of the 2D matrix
    for i in range(1, len(A)):
        if A[i][0] == 0:  // If not obstacle
            paths[i][0] = paths[i-1][0]
              
    # initializing first row of the 2D matrix
    for j in range(1, len(A[0])):
        if A[0][j] == 0:  // If not obstacle
            paths[0][j] = paths[0][j-1]
              
    for i in range(1, len(A)):
      for j in range(1, len(A[0])):
  
        # If current cell is not obstacle
        if A[i][j] == 0:
          paths[i][j] = paths[i-1][j] + paths[i][j-1]
    
    # returning the corner value of the matrix
    return paths[-1][-1]
  
  
# Driver Code
A = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
print(uniquePathsWithObstacles(A))

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

Validity of a given Tic-Tac-Toe


board configuration

Validity of a given Tic-Tac-Toe board configuration - GeeksforGeeks


A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is
valid, i.e., is it possible to reach this board position after some moves or not.
Note that every arbitrary filled grid of 9 spaces isn’t valid e.g. a grid filled with 3 X and 6
O isn’t valid situation because each player needs to take alternate turns.

Input is given as a 1D array of size 9.

Input: board[] = {'X', 'X', 'O',


'O', 'O', 'X',

2222
Chapter 327. Validity of a given Tic-Tac-Toe board configuration

'X', 'O', 'X'};


Output: Valid

Input: board[] = {'O', 'X', 'X',


'O', 'X', 'X',
'O', 'O', 'X'};
Output: Invalid
(Both X and O cannot win)

Input: board[] = {'O', 'X', ' ',


' ', ' ', ' ',
' ', ' ', ' '};
Output: Valid
(Valid board with only two moves played)

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.

1) countX == countO or countX == countO + 1


2) If O is in win condition then check
a) If X also wins, not valid
b) If xbox != obox , not valid
3) If X is in win condition then check if xCount is
one more than oCount or not

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++

// C++ program to check whether a given tic tac toe


// board is valid or not
#include <iostream>
using namespace std;
  
// This matrix is used to find indexes to check all
// possible wining triplets in board[0..8]
int win[8][3] = {{0, 1, 2}, // Check first row.
                {3, 4, 5}, // Check second Row
                {6, 7, 8}, // Check third Row
                {0, 3, 6}, // Check first column
                {1, 4, 7}, // Check second Column
                {2, 5, 8}, // Check third Column
                {0, 4, 8}, // Check first Diagonal
                {2, 4, 6}}; // Check second Diagonal
  
// Returns true if character 'c' wins. c can be either
// 'X' or 'O'
bool isCWin(char *board, char c)
{
    // Check all possible winning combinations
    for (int i=0; i<8; i++)
        if (board[win[i][0]] == c &&
            board[win[i][1]] == c &&
            board[win[i][2]] == c )
            return true;
    return false;
}
  
// Returns true if given board is valid, else returns false
bool isValid(char board[9])
{
    // Count number of 'X' and 'O' in the given board
    int xCount=0, oCount=0;
    for (int i=0; i<9; i++)
    {
    if (board[i]=='X') xCount++;
    if (board[i]=='O') oCount++;
    }
  
    // Board can be valid only if either xCount and oCount
    // is same or xount is one more than oCount
    if (xCount==oCount || xCount==oCount+1)
    {
        // Check if 'O' is winner
        if (isCWin(board, 'O'))

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

# Python3 program to check whether a given tic tac toe


# board is valid or not
  
# Returns true if char wins. Char can be either
# 'X' or 'O'
def win_check(arr, char):
    # Check all possible winning combinations
    matches = [[0, 1, 2], [3, 4, 5],
               [6, 7, 8], [0, 3, 6],
               [1, 4, 7], [2, 5, 8],
               [0, 4, 8], [2, 4, 6]]
  
    for i in range(8):
        if(arr[matches[i][0]] == char and
            arr[matches[i][1]] == char and

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:

Given board is valid

2226
Chapter 327. Validity of a given Tic-Tac-Toe board configuration

Thanks to Utkarsh for suggesting this solution.


Improved By : jaysiyaram

Source

https://www.geeksforgeeks.org/validity-of-a-given-tic-tac-toe-board-configuration/

2227
Chapter 328

Variance and
standard-deviation of a matrix

Variance and standard-deviation of a matrix - GeeksforGeeks


Prerequisite – Mean, Variance and Standard Deviation, Variance and Standard Deviation
of an array
Given a matrix of size n*n. We have to calculate variance and standard-deviation of given
matrix.
Examples :

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

Here mean is 5 and variance is approx 6.66


Below is code implementation:
C++

// CPP program to find mean and


// variance of a matrix.
#include <bits/stdc++.h>
using namespace std;
  
// variance function declaration
int variance(int, int, int);
  
// Function for calculating mean
int mean(int a[][3], int n)
{
    // Calculating sum
    int sum = 0;
    for (int  i = 0; i < n; i++) 
        for (int j = 0; j < n; j++)
            sum += a[i][j];
      
    // Returning mean
    return sum / (n * n);
}
  
// Function for calculating variance
int variance(int a[][3], 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

2229
Chapter 328. Variance and standard-deviation of a matrix

    for (int i = 0; i < n; i++) 


        for (int j = 0; j < n; j++)
            sum += a[i][j];    
  
    return sum / (n * n);
}
  
// driver program
int main()
{
    // declaring and initializing matrix
    int mat[3][3] = { { 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
    int dev = sqrt(var);
  
    // displaying variance and deviation
     cout << "Mean: " << m << "\n"
          << "Variance: " << var << "\n"
          << "Deviation: " << dev << "\n";
    return 0;
}

Java

// Java program to find mean 


// and variance of a matrix.
import java.io.*;
  
class GFG
{
// Function for 
// calculating mean
static int mean(int a[][], 
                int n)
{
    // Calculating sum
    int sum = 0;
    for (int i = 0; i < n; i++) 
        for (int j = 0; j < n; j++)

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#

// C# program to find mean 


// and variance of a matrix.
using System;
  
class GFG
{
      
// Function for 
// calculating mean
static int mean(int [,]a, 
                int n)
{
    // Calculating sum
    int sum = 0;
    for (int i = 0; i < n; i++) 
        for (int j = 0; j < n; j++)
            sum += a[i, j];
      
    // Returning mean
    return sum / (n * n);
}
  
// Function for 
// calculating variance
static int variance(int [,]a, 
                    int n, int m)

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

Ways of filling matrix such that product of all rows and all columns are equal to unity -
GeeksforGeeks

We are given three values , and where is number of rows in matrix, is


number of columns in the matrix and is the number that can have only two values -1 and
1. Our aim is to find the number of ways of filling the matrix of such that the
product of all the elements in each row and each column is equal to . Since the number
of ways can be large we will output
Examples:

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++

// CPP program to find number of ways to fill


// a matrix under given constraints
#include <bits/stdc++.h>
using namespace std;
  
#define mod 100000007
  
/* Returns a raised power t under modulo mod */
long long modPower(long long a, long long t)
{
    long long 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
long countWays(int n, int m, int k)
{
    // 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 && (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 || m == 1)
        return 1;

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

// Java program to find number of ways to fill


// a matrix under given constraints
import java.io.*;
  
class Example {
  
    final static long mod = 100000007;
  
    /* Returns a raised power t under modulo mod */
    static long modPower(long a, long t, long mod)
    {
        long now = a, ret = 1;
  
        // Counting number of ways of filling the
        // matrix
        while (t > 0) {
            if (t % 2 == 1)
                ret = now * (ret % mod);
            now = now * (now % mod);
            t >>= 1;
        }
        return ret;
    }
  

2238
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity

    // Function calculating the answer


    static long countWays(int n, int m, int k)
    {
        // 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 (n == 1 || m == 1)
            return 1;
  
        // If there is one row or one column then
        // there is only one way of filling the matrix
        else if ((n + m) % 2 == 1 && k == -1)
            return 0;
  
       // 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)2, n - 1, mod),
                                    m - 1, mod) % mod);
    }
  
    // Driver function for the program
    public static void main(String args[]) throws IOException
    {
        int n = 2, m = 7, k = 1;
        System.out.println(countWays(n, m, k));
    }
}

C#

// C# program to find number of ways to fill


// a matrix under given constraints
using System;
  
class Example
{
  
    static long mod = 100000007;
  
    // Returns a raised power t 
    // under modulo mod 
    static long modPower(long a, long t,
                         long mod)
    {
        long now = a, ret = 1;
  
        // Counting number of ways 

2239
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity

        // of filling the


        // matrix
        while (t > 0)
        {
            if (t % 2 == 1)
                ret = now * (ret % mod);
            now = now * (now % mod);
            t >>= 1;
        }
        return ret;
    }
  
    // Function calculating the answer
    static long countWays(int n, int m,
                          int k)
    {
        // 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 (n == 1 || m == 1)
            return 1;
  
        // If there is one row or one
        // column then there is only 
        // one way of filling the matrix
        else if ((n + m) % 2 == 1 && k == -1)
            return 0;
  
        // 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)2, n - 1, 
                         mod), m - 1, mod) % mod);
                                      
    }
  
    // Driver Code
    public static void Main() 
    {
        int n = 2, m = 7, k = 1;
        Console.WriteLine(countWays(n, m, k));
    }
}
  

2240
Chapter 329. Ways of filling matrix such that product of all rows and all columns are
equal to unity

// This code is contributed by vt_m.

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

The time complexity of above solution is .


Improved By : vt_m

Source

https://www.geeksforgeeks.org/ways-filling-matrix-product-rows-columns-equal-unity/

2242
Chapter 330

Zigzag (or diagonal) traversal of


Matrix

Zigzag (or diagonal) traversal of Matrix - GeeksforGeeks


Improved By : ChitraNayal

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

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:

Input : mat= [[10, 20, 30, 40],


[15, 25, 35, 45],
[27, 29, 37, 48],
[32, 33, 39, 50]]

Output : Elements of matrix in sorted order


[10, 15, 20, 25, 27, 29, 30, 32,
33, 35, 37, 39, 40, 45, 48, 50]

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.

# Function to print all elements in sorted order


# from row and column wise sorted matrix
from heapq import merge
  

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:

Elements of matrix in sorted order


[10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50]

Source

https://www.geeksforgeeks.org/heapq-python-print-elements-sorted-order-row-column-wise-sorted-matrix/

2245

S-ar putea să vă placă și