算法中的矩阵切换值矩阵、算法

2023-09-11 02:46:42 作者:顾我安稳

还有的 N A矩阵X M ,每个元素为 0 1 。我们选择特定的研究 C (这样 1< =为r = N 1< = C< = M )和(0,0)来(R-1,C-1),我们切换值。也就是说, 0 变成 1 1 变成 0

基本上,每一个的移动的是切换所有值的任意的左上的子矩阵我们原来的矩阵。

我需要编写一个函数来计算的最小的举动,使得矩阵中的所有元素最终在1,但没有得到该怎么办呢号码。请大家帮帮忙。

例如,在下面的矩阵(N == 2和M == 4):

  0 1 0 0
1 0 0 1
 

在做移动之后(2,1)我们最终会完成这个矩阵:(注意其余在第一列的切换值和不变的值基体中。)

  1 1 0 0
0 0 0 1
 
矩阵算法

解决方案

下面应该给你一个想法。

如果你从右下角开始并遍历矩阵反了,你可以得到的行动的数量。

让我们称之为移动(R,C)为pressing的按钮 R,C

因此​​,例如,如果 N-1,M-1 项是零,那么你将不得不preSS一个按钮 N-1,M-1 。随后面前的所有应征作品须得到切换。

现在你检查本作的最后一排向后每个条目。接着检查此为在最后一列向后每个条目。

而不是实际切换的所有条目,你可以保持一个计数的'列'的同时遍历行和时间,同时遍历一列一列被切换次数切换的次数。

现在减少N的1和M 1和重复。每个条目的present值应为: 原值^次数其列已打开^次数其行已打开&放大器; 1。

There's a matrix of NxM, with each element as 0 or 1. We select a specific r, c (such that 1<=r<=N and 1<=c<=M) and starting from (0,0) to (r-1,c-1), we toggle the values. That is, 0 becomes 1 and 1 becomes 0.

Basically, each "move" is to toggle all the values in an arbitrary top-left sub-matrix of our original matrix.

I need to write a function to calculate the minimum number of moves such that all elements of the matrix end up at 1, but not getting how to do it. Please help.

For example, in the following matrix (N == 2 and M == 4):

0  1  0  0
1  0  0  1

after doing the move (2, 1) we'll end up with this matrix: (note the toggled values in the first column and unchanged values in the rest of the matrix.)

1  1  0  0
0  0  0  1

解决方案

Following should give you an idea.

If you start from the right bottom corner and traverse the matrix backwards, you can get the number of 'moves'.

Lets call move(r,c) as pressing the button at r,c.

So for example, if the N-1,M-1 entry is a zero, then you will have to press a button at N-1,M-1. Subsequently all entries before it shall get toggled.

Now you check this for each entry in the last row backwards. Subsequently check this for each entry in the last column backwards.

Instead of actually toggling all the entries, you can keep a count for the number of times a 'column' is toggled while traversing a row and the number of times a row is toggled while traversing a column.

Now decrease N by 1 and M by 1 and repeat. The present value of each entry shall be: Original value ^ number of times its column has been toggled ^ number of times its row has been toggled & 1.