Suppose, we are provided with a matrix of the size n*n, containing integer numbers. We have to find out if all the rows of that matrix are circular rotations of its previous row. In case of first row, it should be a circular rotation of the n-th row.
So, if the input is like
B | A | D | C |
C | B | A | D |
D | C | B | A |
A | D | C | B |
then the output will be True.
To solve this, we will follow these steps −
- concat := blank string
- for i in range 0 to number of rows, do
- concat := concat concatenate "-" concatenate matrix[0,i]
- concat := concat concatenate concat
- for i in range 1 to size of matrix, do
- curr_row := blank string
- for j in range 0 to number of columns, do
- curr_row := curr_row concatenate "-" concatenate matrix[i,j]
- if curr_row is present in string concat, then
- return True
- return False
Example
Let us see the following implementation to get better understanding −
def solve(matrix) : concat = "" for i in range(len(matrix)) : concat = concat + "-" + str(matrix[0][i]) concat = concat + concat for i in range(1, len(matrix)) : curr_row = "" for j in range(len(matrix[0])) : curr_row = curr_row + "-" + str(matrix[i][j]) if (concat.find(curr_row)) : return True return False matrix = [['B', 'A', 'D', 'C'], ['C', 'B', 'A', 'D'], ['D', 'C', 'B', 'A'], ['A', 'D', 'C', 'B']] print(solve(matrix))
Input
[['B', 'A', 'D', 'C'], ['C', 'B', 'A', 'D'], ['D', 'C', 'B', 'A'], ['A', 'D', 'C', 'B']]
Output
True