check if a matrix of row are circular rotation each other




Check if all rows of a matrix are circular rotations of each other


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


Output:
?
package com.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermutationMatrix {

public static void main(String[] args) {
int m = 4, n = 4;
int mat[][] = { { 3, 1, 4, 2 }, { 1, 6, 9, 3 }, { 1, 2, 3, 4 },
{ 4, 3, 2, 1 } };
permutatedRows(mat, m, n);

}

// Function to find all permuted rows of a given row r
public static void permutatedRows(int mat[][], int m, int n) {
List<Integer> list = null;
List<Integer> list2 = null;
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < m; i++) {
list = new ArrayList<Integer>();
for (int j = 0; j < n; j++) {
list.add(mat[i][j]);
}
Collections.sort(list);

if (map.size() > 0 && map.containsKey(list.toString())) {
map.put(list.toString(), map.get(list.toString()) + 1);
} else {
map.put(list.toString(), 1);
}
}

for (int i = 0; i < m; i++) {
list2 = new ArrayList<Integer>();
for (int j = 0; j < n; j++) {
list2.add(mat[i][j]);
}
Collections.sort(list2);
if (map.size() > 0 && map.containsKey(list2.toString())
&& map.get(list2.toString()) > 1) {
for (int j = 0; j < n; j++) {
System.out.print(mat[i][j] + ",");
}
System.out.println();

}
}

}

}



Output:
?
3,1,4,2,
1,2,3,4,
4,3,2,1,





Previous
Next Post »