JavaScript程序用于检查矩阵的所有行是否彼此为循环旋转

JavaScript程序用于检查矩阵的所有行是否彼此为循环旋转

Matrix is a kind of 2-D array in which there is an array of fixed arrays that defines the rows and for each index of this array there are fixed length arrays present and the length of these arrays defines the number of columns present in the matrix. We can store any kind of data type in these cells provided by the matrix.

We will be provided with a matrix and each row contains some integers and we have to check if each row is the rotation of one another or not. Rotation of each other means by some number or left or right rotations we can produce the same combination of each row.

Example 1

让我们假设给定的矩阵是:

  1. mat = [ [1, 2, 3], [2, 3, 1], [3, 1, 2]]Output: Yes

登录后复制

Explanation: Assuming the first row is constant and rotating the remaining one we can get the result as:

立即学习“Java免费学习笔记(深入)”;

By rotating the second row one time to the right and rotating the second row two times to the right we can make both same as the first row.

Example 2

的翻译为:

示例2

  1. mat = [ [1, 2, 3], [ 2, 1, 3], [ 1, 2, 3]]Output: No

登录后复制

解释:在上面的矩阵中,第一行和第三行是相同的,但我们无法通过任意次数的旋转将第二行转换为第一行。

Approach

We have seen a proper example for understanding of the problem now let us see the steps to implement the code −

首先,我们将定义一个函数rotate,使用两个指针和交换技术来旋转作为参数传递给它的数组的元素。

之后,我们将定义检查函数,并将给定的矩阵传递给检查函数。

在该函数中,我们首先通过获取行和列的数量来获取矩阵的长度,并使用for循环从第1行到最后一行与第0行进行比较。

如果当前行与第一行相同,则我们将跳过到下一行。

否则,我们将调用 rotate 函数,并将给定的行旋转到其下一个旋转位置。

We will do this process until we find the same array as the zeroth row or length of columns numbers of times.

If the current row is not equal to the zeroth even after the maximum rotations then we will return false.

如果所有的行最终变得相等,那么我们将返回true。

Example

在下面的示例中,我们检查矩阵的所有行是否是彼此的循环旋转。输入和预期输出如下所示。

输入:matrix = [ [ 1, 2, 3 ], [ 2, 3, 1 ], [ 3, 1, 2 ] ]

Output: Yes

  1. // function to rotate the given arrayfunction rotate(arr){ var l = 0; var r = arr.length-1; while(l

    输出

    The given matrix is: [ [ 1, 2, 3 ], [ 2, 3, 1 ], [ 3, 1, 2 ] ]Yes, all the rows of the matrix are circular rotation of each other
  2. 登录后复制

  3. 时间和空间复杂度

  4. The time complexity of the above code is O(N*M*M) where N is the number or rows and M is the number of columns present in the given matrix. We are traversing over the matrix row wise gives the factor or N and for comparison and rotations of the rows givens the factor or M*M.

  5. 上述代码的空间复杂度为O(1),因为我们没有使用任何额外的空间。

  6. Conclusion

  7. 在本教程中,我们已经实现了JavaScript程序,通过旋转每一行并与第一行进行比较,来检查给定矩阵的所有行是否彼此为循环旋转。我们使用了两个指针和交换方法来旋转给定矩阵的行。上述代码的时间复杂度为O(N*M*M),空间复杂度为O(1)。

  8. 以上就是JavaScript程序用于检查矩阵的所有行是否彼此为循环旋转的详细内容,更多请关注【创想鸟】其它相关文章!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
编程技术

JavaScript程序以找到最长的双峰子序列 | DP-15

2025-3-7 18:13:47

编程技术

解释一下JavaScript中的MUL()函数

2025-3-7 18:13:54

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
私信列表
搜索