📌  相关文章
📜  Java程序检查矩阵的所有行是否相互循环

📅  最后修改于: 2022-05-13 01:55:06.357000             🧑  作者: Mango

Java程序检查矩阵的所有行是否相互循环

给定一个 n*n 大小的矩阵,任务是找出所有行是否是彼此的圆形旋转。

例子:

Input: mat[][] = 1, 2, 3
                 3, 1, 2
                 2, 3, 1
Output:  Yes
All rows are rotated permutation
of each other.

Input: mat[3][3] = 1, 2, 3
                   3, 2, 1
                   1, 3, 2
Output:  No
Explanation : As 3, 2, 1 is not a rotated or 
circular permutation of 1, 2, 3

这个想法是基于下面的文章。
检查字符串是否相互旋转的程序

脚步 :

  1. 创建一个由第一行元素组成的字符串并将该字符串与其自身连接,以便可以有效地执行字符串搜索操作。让这个字符串为 str_cat。
  2. 遍历所有剩余的行。对于要遍历的每一行,创建一个包含当前行元素的字符串str_curr。如果 str_curr 不是 str_cat 的子字符串,则返回 false。
  3. 返回真。

下面是上述步骤的实现。

Java
// Java program to check if all rows of a matrix 
// are rotations of each other 
class GFG 
{
  
    static int MAX = 1000;
  
    // Returns true if all rows of mat[0..n-1][0..n-1] 
    // are rotations of each other. 
    static boolean isPermutedMatrix(int mat[][], 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 + "-" + String.valueOf(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 + "-" + String.valueOf(mat[i][j]);
            }
  
            // Check if the current string is present in 
            // the concatenated string or not 
            if (str_cat.contentEquals(curr_str)) 
            {
                return false;
            }
        }
  
        return true;
    }
  
    // Drivers code 
    public static void main(String[] args) 
    {
        int n = 4;
        int mat[][] = {{1, 2, 3, 4},
        {4, 1, 2, 3},
        {3, 4, 1, 2},
        {2, 3, 4, 1}
        };
        if (isPermutedMatrix(mat, n)) 
        {
            System.out.println("Yes");
        }
        else
        {
            System.out.println("No");
        }
    }
}
  
/* This code contributed by PrinciRaj1992 */


输出:

Yes

有关详细信息,请参阅有关检查矩阵的所有行是否彼此圆形旋转的完整文章!