给定具有0和1的NxN矩阵。将包含0
的每一行设置为所有0
,并将包含0
的每一列设置为所有0
。
例如
1 0 1 1 0
0 1 1 1 0
1 1 1 1 1
1 0 1 1 1
1 1 1 1 1
结果
0 0 0 0 0
0 0 0 0 0
0 0 1 1 0
0 0 0 0 0
0 0 1 1 0
微软工程师告诉我,有一个解决方案不涉及额外的内存,只有两个布尔变量和一个通道,所以我正在寻找答案。
BTW,想象它是一个位矩阵,因此只允许1s和0s在矩阵中。答案 0 :(得分:97)
好的,所以我很累,因为它在这里是3AM,但我首先尝试在矩阵中的每个数字上准确地进行2次传递,因此在O(NxN)中它与矩阵的大小呈线性关系。
我使用第一列和第一行作为标记来了解行/列只有1的位置。然后,有2个变量l和c要记住第一行/列是否也都是1。 所以第一遍设置标记并将其余部分重置为0。
第二遍在行和列标记为1的位置设置1,并根据l和c重置第一行/列。
我强烈怀疑我可以在1次传球中完成,因为开始时的方格依赖于最后的方格。也许我的第二次传球可以提高效率......
import pprint
m = [[1, 0, 1, 1, 0],
[0, 1, 1, 1, 0],
[1, 1, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1]]
N = len(m)
### pass 1
# 1 rst line/column
c = 1
for i in range(N):
c &= m[i][0]
l = 1
for i in range(1,N):
l &= m[0][i]
# other line/cols
# use line1, col1 to keep only those with 1
for i in range(1,N):
for j in range(1,N):
if m[i][j] == 0:
m[0][j] = 0
m[i][0] = 0
else:
m[i][j] = 0
### pass 2
# if line1 and col1 are ones: it is 1
for i in range(1,N):
for j in range(1,N):
if m[i][0] & m[0][j]:
m[i][j] = 1
# 1rst row and col: reset if 0
if l == 0:
for i in range(N):
m [i][0] = 0
if c == 0:
for j in range(1,N):
m [0][j] = 0
pprint.pprint(m)
答案 1 :(得分:15)
这不能在一次通过中完成,因为单个位在任何排序中对其之前和之后的位有影响。 IOW无论你通过什么顺序遍历数组,你可能会在0之后变为0,这意味着你必须返回并将之前的1更改为0。
更新
人们似乎认为通过将N限制为某个固定值(比如8),你可以解决这个问题。嗯,这是a)错过了重点,b)不是原来的问题。我不会发布关于排序的问题,并期待一个答案,开始“假设你只想排序8件事......”。
那就是说,如果你知道N实际上只限于8,这是一种合理的方法。我上面的答案回答了没有这种限制的原始问题。
答案 2 :(得分:10)
所以我的想法是使用最后一行/列中的值作为标志来指示相应列/行中的所有值是否为1。
在整个矩阵中使用Zig Zag scan,除了最后一行/列。在每个元素处,您将最终行/列中的值设置为其自身的逻辑AND与当前元素中的值。换句话说,如果你点击0,最后的行/列将被设置为0.如果你是1,最后一行/列中的值只有1已经是1。在任何情况下,将当前元素设置为0。
完成后,如果相应的列/行填充了1,则最后一行/列应该为1。
对最终的行和列进行线性扫描并查找1。在矩阵的主体中的相应元素中设置1,其中最后的行和列都是1。
编码将避免一对一的错误等是很棘手的,但它应该在一次通过中起作用。
答案 3 :(得分:6)
我在这里有一个解决方案,它只需一次运行,并且可以在没有额外内存的情况下进行所有处理(除了增加堆栈)。
它使用递归来延迟写入零,这当然会破坏其他行和列的矩阵:
#include <iostream>
/**
* The idea with my algorithm is to delay the writing of zeros
* till all rows and cols can be processed. I do this using
* recursion:
* 1) Enter Recursive Function:
* 2) Check the row and col of this "corner" for zeros and store the results in bools
* 3) Send recursive function to the next corner
* 4) When the recursive function returns, use the data we stored in step 2
* to zero the the row and col conditionally
*
* The corners I talk about are just how I ensure I hit all the row's a cols,
* I progress through the matrix from (0,0) to (1,1) to (2,2) and on to (n,n).
*
* For simplicities sake, I use ints instead of individual bits. But I never store
* anything but 0 or 1 so it's still fair ;)
*/
// ================================
// Using globals just to keep function
// call syntax as straight forward as possible
int n = 5;
int m[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 0, 1, 1, 1, 0 },
{ 1, 1, 1, 1, 1 },
{ 1, 0, 1, 1, 1 },
{ 1, 1, 1, 1, 1 }
};
// ================================
// Just declaring the function prototypes
void processMatrix();
void processCorner( int cornerIndex );
bool checkRow( int rowIndex );
bool checkCol( int colIndex );
void zeroRow( int rowIndex );
void zeroCol( int colIndex );
void printMatrix();
// This function primes the pump
void processMatrix() {
processCorner( 0 );
}
// Step 1) This is the heart of my recursive algorithm
void processCorner( int cornerIndex ) {
// Step 2) Do the logic processing here and store the results
bool rowZero = checkRow( cornerIndex );
bool colZero = checkCol( cornerIndex );
// Step 3) Now progress through the matrix
int nextCorner = cornerIndex + 1;
if( nextCorner < n )
processCorner( nextCorner );
// Step 4) Finially apply the changes determined earlier
if( colZero )
zeroCol( cornerIndex );
if( rowZero )
zeroRow( cornerIndex );
}
// This function returns whether or not the row contains a zero
bool checkRow( int rowIndex ) {
bool zero = false;
for( int i=0; i<n && !zero; ++i ) {
if( m[ rowIndex ][ i ] == 0 )
zero = true;
}
return zero;
}
// This is just a helper function for zeroing a row
void zeroRow( int rowIndex ) {
for( int i=0; i<n; ++i ) {
m[ rowIndex ][ i ] = 0;
}
}
// This function returns whether or not the col contains a zero
bool checkCol( int colIndex ) {
bool zero = false;
for( int i=0; i<n && !zero; ++i ) {
if( m[ i ][ colIndex ] == 0 )
zero = true;
}
return zero;
}
// This is just a helper function for zeroing a col
void zeroCol( int colIndex ) {
for( int i=0; i<n; ++i ) {
m[ i ][ colIndex ] = 0;
}
}
// Just a helper function for printing our matrix to std::out
void printMatrix() {
std::cout << std::endl;
for( int y=0; y<n; ++y ) {
for( int x=0; x<n; ++x ) {
std::cout << m[y][x] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
// Execute!
int main() {
printMatrix();
processMatrix();
printMatrix();
}
答案 4 :(得分:4)
我不认为这是可行的。当您在第一个方格上并且其值为1时,您无法知道同一行和列中其他方块的值是什么。所以你必须检查那些,如果有零,返回第一个方块并将其值更改为零。我建议在两次传递中进行 - 第一次传递收集有关哪些行和列必须清零的信息(信息存储在数组中,因此我们使用了一些额外的内存)。第二遍改变了值。我知道这不是你想要的解决方案,但我认为这是一个实用的解决方案。您给出的约束使问题无法解决。
答案 5 :(得分:3)
问题可以一次解决
将矩阵保存在i X j数组中。
1 0 1 1 0
0 1 1 1 0
1 1 1 1 1
1 0 1 1 1
1 1 1 1 1
one each pass save the values of i and j for an element which is 0 in arrays a and b
when first row is scanned a= 1 b = 2,5
when second row is scanned a=1,2 b= 1,2,5
when third row is scanned no change
when fourth row is scanned a= 1,2,4 and b= 1,2,5
when fifth row is scanned no change .
现在将所有值打印为0,以保存在a和b中的i和j的值 其余值为1即(3,3)(3,4)(5,3)和(5,4)
答案 6 :(得分:3)
我可以使用两个整数变量和两个遍(最多32行和列......)
bool matrix[5][5] =
{
{1, 0, 1, 1, 0},
{0, 1, 1, 1, 0},
{1, 1, 1, 1, 1},
{1, 0, 1, 1, 1},
{1, 1, 1, 1, 1}
};
int CompleteRows = ~0;
int CompleteCols = ~0;
// Find the first 0
for (int row = 0; row < 5; ++row)
{
for (int col = 0; col < 5; ++col)
{
CompleteRows &= ~(!matrix[row][col] << row);
CompleteCols &= ~(!matrix[row][col] << col);
}
}
for (int row = 0; row < 5; ++row)
for (int col = 0; col < 5; ++col)
matrix[row][col] = (CompleteRows & (1 << row)) && (CompleteCols & (1 << col));
答案 7 :(得分:1)
不错的挑战。这种解决方案只使用在堆栈上创建的两个布尔值,但由于函数是递归的,因此在堆栈上多次创建布尔值。
typedef unsigned short WORD;
typedef unsigned char BOOL;
#define true 1
#define false 0
BYTE buffer[5][5] = {
1, 0, 1, 1, 0,
0, 1, 1, 1, 0,
1, 1, 1, 1, 1,
1, 0, 1, 1, 1,
1, 1, 1, 1, 1
};
int scan_to_end(BOOL *h,BOOL *w,WORD N,WORD pos_N)
{
WORD i;
for(i=0;i<N;i++)
{
if(!buffer[i][pos_N])
*h=false;
if(!buffer[pos_N][i])
*w=false;
}
return 0;
}
int set_line(BOOL h,BOOL w,WORD N,WORD pos_N)
{
WORD i;
if(!h)
for(i=0;i<N;i++)
buffer[i][pos_N] = false;
if(!w)
for(i=0;i<N;i++)
buffer[pos_N][i] = false;
return 0;
}
int scan(int N,int pos_N)
{
BOOL h = true;
BOOL w = true;
if(pos_N == N)
return 0;
// Do single scan
scan_to_end(&h,&w,N,pos_N);
// Scan all recursive before changeing data
scan(N,pos_N+1);
// Set the result of the scan
set_line(h,w,N,pos_N);
return 0;
}
int main(void)
{
printf("Old matrix\n");
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[0][0],(WORD)buffer[0][1],(WORD)buffer[0][2],(WORD)buffer[0][3],(WORD)buffer[0][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[1][0],(WORD)buffer[1][1],(WORD)buffer[1][2],(WORD)buffer[1][3],(WORD)buffer[1][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[2][0],(WORD)buffer[2][1],(WORD)buffer[2][2],(WORD)buffer[2][3],(WORD)buffer[2][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[3][0],(WORD)buffer[3][1],(WORD)buffer[3][2],(WORD)buffer[3][3],(WORD)buffer[3][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[4][0],(WORD)buffer[4][1],(WORD)buffer[4][2],(WORD)buffer[4][3],(WORD)buffer[4][4]);
scan(5,0);
printf("New matrix\n");
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[0][0],(WORD)buffer[0][1],(WORD)buffer[0][2],(WORD)buffer[0][3],(WORD)buffer[0][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[1][0],(WORD)buffer[1][1],(WORD)buffer[1][2],(WORD)buffer[1][3],(WORD)buffer[1][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[2][0],(WORD)buffer[2][1],(WORD)buffer[2][2],(WORD)buffer[2][3],(WORD)buffer[2][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[3][0],(WORD)buffer[3][1],(WORD)buffer[3][2],(WORD)buffer[3][3],(WORD)buffer[3][4]);
printf( "%d,%d,%d,%d,%d \n", (WORD)buffer[4][0],(WORD)buffer[4][1],(WORD)buffer[4][2],(WORD)buffer[4][3],(WORD)buffer[4][4]);
system( "pause" );
return 0;
}
扫描方式如下:
s,s,s,s,s
s,0,0,0,0
s,0,0,0,0
s,0,0,0,0
s,0,0,0,0
0,s,0,0,0
s,s,s,s,s
0,s,0,0,0
0,s,0,0,0
0,s,0,0,0
等等
然后在每个扫描函数的返回时更改此模式中的值。 (自下而上):
0,0,0,0,c
0,0,0,0,c
0,0,0,0,c
0,0,0,0,c
c,c,c,c,c
0,0,0,c,0
0,0,0,c,0
0,0,0,c,0
c,c,c,c,c
0,0,0,c,0
等等
答案 8 :(得分:1)
需要两次传递的另一个解决方案是水平和垂直累积AND:
1 0 1 1 0 | 0
0 1 1 1 0 | 0
1 1 1 1 1 | 1
1 0 1 1 1 | 0
1 1 1 1 1 | 1
----------+
0 0 1 1 0
我以为我可以使用parity bits,Hamming codes或dynamic programming设计这样的算法,可能使用这两个布尔值作为2位数,但我还没有成功
您能否请与工程师重新核对问题陈述并告诉我们?如果 确实是一个解决方案,我想继续解决这个问题。
答案 9 :(得分:1)
保留一个变量来跟踪ANDed在一起的所有行。
如果一行为-1(全1),则使下一行成为对该变量的引用
如果一行不是,那就是0.你可以一次完成所有事情。伪代码:
foreach (my $row) rows {
$andproduct = $andproduct & $row;
if($row != -1) {
zero out the row
} else {
replace row with a reference to andproduct
}
}
这应该在一次通过中完成 - 但是这里假设N足够小,CPU可以对单行进行算术运算,否则你需要循环每一行来确定如果它全部是1,我相信。但是考虑到你在询问algos而不是限制我的硬件,我只想用“构建支持N位算术的CPU ......”开始我的答案。
这是一个如何在C中完成的示例。注意我认为值和arr一起表示数组,p和numproduct是我的迭代器和AND产品变量用于实现问题。 (我可以使用指针算法循环使用arr来验证我的工作,但一次就够了!)
int main() {
int values[] = { -10, 14, -1, -9, -1 }; /* From the problem spec, converted to decimal for my sanity */
int *arr[5] = { values, values+1, values+2, values+3, values+4 };
int **p;
int numproduct = 127;
for(p = arr; p < arr+5; ++p) {
numproduct = numproduct & **p;
if(**p != -1) {
**p = 0;
} else {
*p = &numproduct;
}
}
/* Print our array, this loop is just for show */
int i;
for(i = 0; i < 5; ++i) {
printf("%x\n",*arr[i]);
}
return 0;
}
这会产生0,0,6,0,6,这是给定输入的结果。
或者在PHP中,如果人们认为我在C中的堆叠游戏是作弊的(我建议你不要这样做,因为我应该能够以我喜欢的方式存储矩阵):
<?php
$values = array(-10, 14, -1, -9, -1);
$numproduct = 127;
for($i = 0; $i < 5; ++$i) {
$numproduct = $numproduct & $values[$i];
if($values[$i] != -1) {
$values[$i] = 0;
} else {
$values[$i] = &$numproduct;
}
}
print_r($values);
我错过了什么吗?
答案 10 :(得分:1)
实际上。如果你只是想运行算法并打印出结果(即不恢复它们,那么这可以很容易地在一次通过中完成。当你在运行算法时尝试修改数组时会遇到麻烦。
这是我的解决方案它只涉及对给定(i,j)元素的行/列值进行AND运算并将其打印出来。
#include <iostream>
#include "stdlib.h"
void process();
int dim = 5;
bool m[5][5]{{1,0,1,1,1},{0,1,1,0,1},{1,1,1,1,1},{1,1,1,1,1},{0,0,1,1,1}};
int main() {
process();
return 0;
}
void process() {
for(int j = 0; j < dim; j++) {
for(int i = 0; i < dim; i++) {
std::cout << (
(m[0][j] & m[1][j] & m[2][j] & m[3][j] & m[4][j]) &
(m[i][0] & m[i][1] & m[i][2] & m[i][3] & m[i][4])
);
}
std::cout << std::endl;
}
}
答案 11 :(得分:1)
我试图在C#中解决这个问题。
除了实际的矩阵之外,我使用了两个循环变量(i和j),n代表了它的维度
我试过的逻辑是:
代码:
void Evaluate(bool [,] matrix, int n)
{
bool tempvar1, tempvar2;
for (var i = 0; i < n; i++)
{
tempvar1 = matrix[i, i];
tempvar2 = matrix[n - i - 1, n - i - 1];
var j = 0;
for (j = 0; j < n; j++)
{
if ((i < n/2) || (((n % 2) == 1) && (i == n/2) && (j <= i)))
{
// store the row and col & results in corner cells of concentric squares
tempvar1 &= matrix[j, i];
matrix[i, i] &= matrix[i, j];
tempvar2 &= matrix[n - j - 1, n - i - 1];
matrix[n - i - 1, n - i - 1] &= matrix[n - i - 1, n - j - 1];
}
else
{
// skip corner cells of concentric squares
if ((j == i) || (j == n - i - 1)) continue;
// calculate the & values for rest of them
matrix[i, j] = matrix[i, i] & matrix[n - j - 1, j];
matrix[n - i - 1, j] = matrix[n - i - 1, n - i - 1] & matrix[n - j - 1, j];
if ((i == n/2) && ((n % 2) == 1))
{
// if n is odd
matrix[i, n - j - 1] = matrix[i, i] & matrix[j, n - j - 1];
}
}
}
if ((i < n/2) || (((n % 2) == 1) && (i <= n/2)))
{
// transfer the values from temp variables to appropriate corner cells of its corresponding square
matrix[n - i - 1, i] = tempvar1;
matrix[i, n - i - 1] = tempvar2;
}
else if (i == n - 1)
{
// update the values of corner cells of each concentric square
for (j = n/2; j < n; j++)
{
tempvar1 = matrix[j, j];
tempvar2 = matrix[n - j - 1, n - j - 1];
matrix[j, j] &= matrix[n - j - 1, j];
matrix[n - j - 1, j] &= tempvar2;
matrix[n - j - 1, n - j - 1] &= matrix[j, n - j - 1];
matrix[j, n - j - 1] &= tempvar1;
}
}
}
}
答案 12 :(得分:1)
好的,这是
的解决方案#include <stdio.h> #define BIT30 (1<<24) #define COLMASK 0x108421L #define ROWMASK 0x1fL
unsigned long long STARTGRID =
((0x10 | 0x0 | 0x4 | 0x2 | 0x0) << 20) |
((0x00 | 0x8 | 0x4 | 0x2 | 0x0) << 15) |
((0x10 | 0x8 | 0x4 | 0x2 | 0x1) << 10) |
((0x10 | 0x0 | 0x4 | 0x2 | 0x1) << 5) |
((0x10 | 0x8 | 0x4 | 0x2 | 0x1) << 0);
void dumpGrid (char* comment, unsigned long long theGrid) {
char buffer[1000];
buffer[0]='\0';
printf ("\n\n%s\n",comment);
for (int j=1;j<31; j++) {
if (j%5!=1)
printf( "%s%s", ((theGrid & BIT30)==BIT30)? "1" : "0",(((j%5)==0)?"\n" : ",") );
theGrid = theGrid << 1;
}
}
int main (int argc, const char * argv[]) {
unsigned long long rowgrid = STARTGRID;
unsigned long long colGrid = rowgrid;
unsigned long long rowmask = ROWMASK;
unsigned long long colmask = COLMASK;
dumpGrid("Initial Grid", rowgrid);
for (int i=0; i<5; i++) {
if ((rowgrid & rowmask)== rowmask) rowgrid |= rowmask;
else rowgrid &= ~rowmask;
if ((colGrid & colmask) == colmask) colmask |= colmask;
else colGrid &= ~colmask;
rowmask <<= 5;
colmask <<= 1;
}
colGrid &= rowgrid;
dumpGrid("RESULT Grid", colGrid);
return 0;
}
答案 13 :(得分:0)
下面的代码创建一个大小为m,n的矩阵。首先确定矩阵的尺寸。我想随机填充矩阵[m] [n],数字在0..10之间。然后创建另一个相同尺寸的矩阵,并用-1s(最终矩阵)填充它。然后遍历初始矩阵以查看是否会达到0.当您点击位置(x,y)时,转到最终矩阵并将行x填入0,将y填充为0。 在最后读取最终矩阵时,如果值为-1(原始值),则将初始矩阵的相同位置的值复制到最终矩阵。
ini_set
答案 14 :(得分:0)
似乎以下工作,没有额外的空间要求:
首先注意,将行的元素乘以元素所在行的元素,得到所需的值。
为了不使用任何额外的空间(不制作新的矩阵并填充它而是直接对矩阵应用更改),从矩阵的左上角开始并对任何ixi矩阵进行计算(即“开始”)在(0,0))之前考虑任何具有任何索引的元素&gt;岛
希望这有效(没有testet)
答案 15 :(得分:0)
对于C ++中的不同N,这是 TESTED ,并且是:
ONE PASS ,两个BOOLS , NO RECURSION ,没有额外的记忆,绝对大小N
(到目前为止,这里没有一个解决方案可以完成所有这些。)
更具体地说,我很有趣,两个循环计数器都没关系。我有两个const unsigneds,它们只存在而不是每次都为了可读性而被计算。外环的间隔为[0,N],内环的间隔为[1,n - 1]。循环语句在循环中主要存在,非常清楚地表明它实际上只是一次通过。
算法策略:
第一个技巧是给我们矩阵本身的一行和一列来累积矩阵的内容,通过将我们真正需要知道的所有内容从第一行和列卸载到两个布尔值中,可以获得这个内存。第二个技巧是通过使用子矩阵的对称性及其索引来获得两个传递。
算法概要:
模板化C ++实施:
template<unsigned n>
void SidewaysAndRowColumn(int((&m)[n])[n]) {
bool fcol = m[0][0] ? true : false;
bool frow = m[0][0] ? true : false;
for (unsigned d = 0; d <= n; ++d) {
for (unsigned i = 1; i < n; ++i) {
switch (d) {
case 0:
frow = frow && m[d][i];
fcol = fcol && m[i][d];
break;
default:
{
unsigned const rd = n - d;
unsigned const ri = n - i;
if (d * n + i < rd * n + ri)
{
m[ d][ 0] &= m[ d][ i];
m[ 0][ d] &= m[ i][ d];
m[ 0][ i] &= m[ d][ i];
m[ i][ 0] &= m[ i][ d];
m[rd][ 0] &= m[rd][ri];
m[ 0][rd] &= m[ri][rd];
m[ 0][ri] &= m[rd][ri];
m[ri][ 0] &= m[ri][rd];
}
else
{
m[ d][ i] = m[ d][0] & m[0][ i];
m[rd][ri] = m[rd][0] & m[0][ri];
}
break;
}
case n:
if (!frow)
m[0][i] = 0;
if (!fcol)
m[i][0] = 0;
};
}
}
m[0][0] = (frow && fcol) ? 1 : 0;
}
答案 16 :(得分:0)
这是我的Ruby实现,其中包含测试,这将占用O(MN)空间。如果我们想要实时更新(比如在我们找到零而不是等待找到零的第一个循环时显示结果),我们可以创建另一个类变量,如@output
,每当我们找到零时,我们都会更新{{ 1}}而不是@output
。
@input
答案 17 :(得分:0)
我能想到的最简单的解决方案粘贴在下面。逻辑是在迭代时记录哪个行和列设置为零。
command = ['./JS/ChannelAssign5+1stereo.app/Contents/MacOS/ChannelAssign5+1stereo',
'/Volumes/GRAID/_PREVIEWS/MASTER copy.mov']
p1 = subprocess.Popen(command)
答案 18 :(得分:0)
这是我的解决方案。从代码中可以看出,给定M * N矩阵,一旦检查到该行中的零,它就将整行设置为零。我的解的时间复杂度为O(M * N)。 我正在共享整个类,它有一个用于测试的静态填充数组和一个显示数组方法,用于在控制台中查看结果。
public class EntireRowSetToZero {
static int arr[][] = new int[3][4];
static {
arr[0][0] = 1;
arr[0][1] = 9;
arr[0][2] = 2;
arr[0][3] = 2;
arr[1][0] = 1;
arr[1][1] = 5;
arr[1][2] = 88;
arr[1][3] = 7;
arr[2][0] = 0;
arr[2][1] = 8;
arr[2][2] = 4;
arr[2][3] = 4;
}
public static void main(String[] args) {
displayArr(EntireRowSetToZero.arr, 3, 4);
setRowToZero(EntireRowSetToZero.arr);
System.out.println("--------------");
displayArr(EntireRowSetToZero.arr, 3, 4);
}
static int[][] setRowToZero(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(arr[i][j]==0){
arr[i]=new int[arr[i].length];
}
}
}
return arr;
}
static void displayArr(int[][] arr, int n, int k) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
}
答案 19 :(得分:0)
设置一个标志(这里使用的数字不受限制,我使用-1),然后一旦我们更改所有匹配的行和col,将所有标志替换为零
public class Main {
public static void main(String[] args) {
//test case 1
int[][] multi = new int[][]{
{ 1, 2, 3 },
{ 4, 0, 5 },
{ 0, 6, 7 },
};
//test case 2
int[][] multi2 = new int[][]{
{ 1, 0, 1, 1, 0 },
{ 0, 1, 1, 1, 0 },
{ 1, 1, 1, 1, 1 },
{ 1, 0, 1, 1, 1},
{ 1, 1, 1, 1, 1},
};
TwoDArraySetZero(multi2);
}
static void TwoDArraySetZero(int[][] array){
//iterate through all elements
for(int i = 0 ; i <= array.length-1 ; i++){
for (int j = 0; j <= array.length-1; j++) {
//checking if match with zero
if (array[i][j] == 0){
//set replace with -1 all matching zero row and col if not zero
for (int k = 0; k <= array.length-1 ; k++) {
if(array[i][k] != 0 )
array[i][k] = -1;
if(array[k][j] != 0)
array[k][j]= -1;
}
}
}
}
//print array
for(int i = 0; i <= array.length-1; i++)
{
for(int j = 0; j <= array.length-1; j++)
{
//replace with zero all -1
if(array[i][j] == -1)
array[i][j] = 0;
System.out.printf("%5d ", array[i][j]);
}
System.out.println();
}
}
}
答案 20 :(得分:0)
一次通过 - 我只遍历了一次输入,但使用了一个新数组,只使用了两个额外的布尔变量。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
boolean rowDel = false, colDel = false;
int arr[][] = new int[n][n];
int res[][] = new int[n][n];
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
res[i][j] = arr[i][j];
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (arr[i][j] == 0)
colDel = rowDel = true; //See if we have to delete the
//current row and column
if (rowDel == true){
res[i] = new int[n];
rowDel = false;
}
if(colDel == true){
for (int k = 0; k < n; k++) {
res[k][j] = 0;
}
colDel = false;
}
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
System.out.print(res[i][j]);
}
System.out.println();
}
sc.close();
}
答案 21 :(得分:0)
一次矩阵扫描,两次布尔,没有递归。
如何避免第二次传球? 当零出现在它们的末尾时,需要第二遍来清除行或列。
然而,这个问题可以解决,因为当我们扫描行#i时,我们已经知道行#i-1的行状态。因此,当我们扫描行#i时,如果需要,我们可以同时清除#i-1行。
相同的解决方案适用于列,但我们需要同时扫描行和列,而下一次迭代不会更改数据。
需要两个布尔值来存储第一行和第一列的状态,因为它们的值将在算法的主要部分执行期间被更改。
为避免添加更多布尔值,我们在矩阵的第一行和第一行中存储行和列的“清除”标志。
public void Run()
{
const int N = 5;
int[,] m = new int[N, N]
{{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 1, 0 },
{ 1, 1, 1, 1, 1 },
{ 1, 0, 1, 1, 1 },
{ 1, 1, 1, 1, 1 }};
bool keepFirstRow = (m[0, 0] == 1);
bool keepFirstColumn = keepFirstRow;
for (int i = 1; i < N; i++)
{
keepFirstRow = keepFirstRow && (m[0, i] == 1);
keepFirstColumn = keepFirstColumn && (m[i, 0] == 1);
}
Print(m); // show initial setup
m[0, 0] = 1; // to protect first row from clearing by "second pass"
// "second pass" is performed over i-1 row/column,
// so we use one more index just to complete "second pass" over the
// last row/column
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
// "first pass" - searcing for zeroes in row/column #i
// when i = N || j == N it is additional pass for clearing
// the previous row/column
// j >= i because cells with j < i may be already modified
// by "second pass" part
if (i < N && j < N && j >= i)
{
m[i, 0] &= m[i, j];
m[0, j] &= m[i, j];
m[0, i] &= m[j, i];
m[j, 0] &= m[j, i];
}
// "second pass" - clearing the row/column scanned
// in the previous iteration
if (m[i - 1, 0] == 0 && j < N)
{
m[i - 1, j] = 0;
}
if (m[0, i - 1] == 0 && j < N)
{
m[j, i - 1] = 0;
}
}
Print(m);
}
// Clear first row/column if needed
if (!keepFirstRow || !keepFirstColumn)
{
for (int i = 0; i < N; i++)
{
if (!keepFirstRow)
{
m[0, i] = 0;
}
if (!keepFirstColumn)
{
m[i, 0] = 0;
}
}
}
Print(m);
Console.ReadLine();
}
private static void Print(int[,] m)
{
for (int i = 0; i < m.GetLength(0); i++)
{
for (int j = 0; j < m.GetLength(1); j++)
{
Console.Write(" " + m[i, j]);
}
Console.WriteLine();
}
Console.WriteLine();
}
答案 22 :(得分:0)
没有人使用二进制表格?因为它只有1和0.我们可以使用二进制向量。
def set1(M, N):
'''Set 1/0s on M according to the rules.
M is a list of N integers. Each integer represents a binary array, e.g.,
000100'''
ruler = 2**N-1
for i,v in enumerate(M):
ruler = ruler & M[i]
M[i] = M[i] if M[i]==2**N-1 else 0 # set i-th row to all-0 if not all-1s
for i,v in enumerate(M):
if M[i]: M[i] = ruler
return M
以下是测试:
M = [ 0b10110,
0b01110,
0b11111,
0b10111,
0b11111 ]
print "Before..."
for i in M: print "{:0=5b}".format(i)
M = set1(M, len(M))
print "After..."
for i in M: print "{:0=5b}".format(i)
输出:
Before...
10110
01110
11111
10111
11111
After...
00000
00000
00110
00000
00110
答案 23 :(得分:0)
你可以做这样的事情来使用一个通道但是输入和输出矩阵:
output(x,y) = col(xy) & row(xy) == 2^n
其中col(xy)
是包含点xy
的列中的位; row(xy)
是包含点xy
的行中的位。 n
是矩阵的大小。
然后循环输入。可能是可扩展的,以提高空间效率吗?
答案 24 :(得分:0)
1次传球,2次布尔。我只需要假设迭代中的整数索引不计算。
这不是一个完整的解决方案,但我无法通过这一点。
如果我只能确定0是原始0还是1转换为0,那么我就不必使用-1,这样就行了。
我的输出是这样的:
-1 0 -1 -1 0
0 -1 -1 -1 0
-1 -1 1 1 -1
-1 0 -1 -1 -1
-1 -1 1 1 -1
我的方法的原创性是使用行或列的检查的前半部分来确定它是否包含0而后半部分来设置值 - 这是通过查看x和width-x来完成的y和每次迭代中的高度-y。根据迭代前半部分的结果,如果找到行或列中的0,我会使用迭代的后半部分将1更改为-1。
我刚刚意识到这可以用1布尔值完成,只留下1到......?
我发布这个希望有人可能会说,“啊,就这样做......”(我花了太多时间不发帖。)
这是VB中的代码:
Dim D(,) As Integer = {{1, 0, 1, 1, 1}, {0, 1, 1, 0, 1}, {1, 1, 1, 1, 1}, {1, 1, 1, 1, 1}, {0, 0, 1, 1, 1}}
Dim B1, B2 As Boolean
For y As Integer = 0 To UBound(D)
B1 = True : B2 = True
For x As Integer = 0 To UBound(D)
// Scan row for 0's at x and width - x positions. Halfway through I'll konw if there's a 0 in this row.
//If a 0 is found set my first boolean to false.
If x <= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then
If D(x, y) = 0 Or D(UBound(D) - x, y) = 0 Then B1 = False
End If
//If the boolean is false then a 0 in this row was found. Spend the last half of this loop
//updating the values. This is where I'm stuck. If I change a 1 to a 0 it will cause the column
//scan to fail. So for now I change to a -1. If there was a way to change to 0 yet later tell if
//the value had changed this would work.
If Not B1 Then
If x >= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then
If D(x, y) = 1 Then D(x, y) = -1
If D(UBound(D) - x, y) = 1 Then D(UBound(D) - x, y) = -1
End If
End If
//These 2 block do the same as the first 2 blocks but I switch x and y to do the column.
If x <= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then
If D(y, x) = 0 Or D(y, UBound(D) - x) = 0 Then B2 = False
End If
If Not B2 Then
If x >= (Math.Ceiling((UBound(D) + 1) / 2) - 1) Then
If D(y, x) = 1 Then D(y, x) = -1
If D(y, UBound(D) - x) = 1 Then D(y, UBound(D) - x) = -1
End If
End If
Next
Next
答案 25 :(得分:0)
好吧,我意识到它并不是很匹配,但我在一次传球中使用bool和一个字节而不是两个bool ...得到它。我也不会保证它的效率,但这些类型的问题通常需要的不是最佳解决方案。
private static void doIt(byte[,] matrix)
{
byte zeroCols = 0;
bool zeroRow = false;
for (int row = 0; row <= matrix.GetUpperBound(0); row++)
{
zeroRow = false;
for (int col = 0; col <= matrix.GetUpperBound(1); col++)
{
if (matrix[row, col] == 0)
{
zeroRow = true;
zeroCols |= (byte)(Math.Pow(2, col));
// reset this column in previous rows
for (int innerRow = 0; innerRow < row; innerRow++)
{
matrix[innerRow, col] = 0;
}
// reset the previous columns in this row
for (int innerCol = 0; innerCol < col; innerCol++)
{
matrix[row, innerCol] = 0;
}
}
else if ((int)(zeroCols & ((byte)Math.Pow(2, col))) > 0)
{
matrix[row, col] = 0;
}
// Force the row to zero
if (zeroRow) { matrix[row, col] = 0; }
}
}
}
答案 26 :(得分:0)
我希望你喜欢我的1-pass c#解决方案
您可以使用O(1)检索元素并且只需要 矩阵的一行和一列的空间
bool[][] matrix =
{
new[] { true, false, true, true, false }, // 10110
new[] { false, true, true, true, false }, // 01110
new[] { true, true, true, true, true }, // 11111
new[] { true, false, true, true, true }, // 10111
new[] { true, true, true, true, true } // 11111
};
int n = matrix.Length;
bool[] enabledRows = new bool[n];
bool[] enabledColumns = new bool[n];
for (int i = 0; i < n; i++)
{
enabledRows[i] = true;
enabledColumns[i] = true;
}
for (int rowIndex = 0; rowIndex < n; rowIndex++)
{
for (int columnIndex = 0; columnIndex < n; columnIndex++)
{
bool element = matrix[rowIndex][columnIndex];
enabledRows[rowIndex] &= element;
enabledColumns[columnIndex] &= element;
}
}
for (int rowIndex = 0; rowIndex < n; rowIndex++)
{
for (int columnIndex = 0; columnIndex < n; columnIndex++)
{
bool element = enabledRows[rowIndex] & enabledColumns[columnIndex];
Console.Write(Convert.ToInt32(element));
}
Console.WriteLine();
}
/*
00000
00000
00110
00000
00110
*/
答案 27 :(得分:0)
你可以在一次通过中进行排序 - 如果你不计算以随机访问顺序访问矩阵,这就消除了首先进行单通道的好处(缓存一致性/内存带宽) )。
[编辑:简单,但错误的解决方案已删除]
通过两次传递,您应该获得比任何单次传递方法更好的性能:一次用于累积行/列信息,一种用于应用它。以连贯的方式访问数组(按行主顺序);对于超过缓存大小的数组(但其行可以适合缓存),应该从内存中读取数据两次,并存储一次:
void fixmatrix2(int M[][], int rows, int cols) {
bool clearZeroRow= false;
bool clearZeroCol= false;
for(int j=0; j < cols; ++j) {
if( ! M[0][j] ) {
clearZeroRow= true;
}
}
for(int i=1; i < rows; ++i) { // scan/accumulate pass
if( ! M[i][0] ) {
clearZeroCol= true;
}
for(int j=1; j < cols; ++j) {
if( ! M[i][j] ) {
M[0][j]= 0;
M[i][0]= 0;
}
}
}
for(int i=1; i < rows; ++i) { // update pass
if( M[i][0] ) {
for(int j=0; j < cols; ++j) {
if( ! M[j][0] ) {
M[i][j]= 0;
}
}
} else {
for(int j=0; j < cols; ++j) {
M[i][j]= 0;
}
}
if(clearZeroCol) {
M[i][0]= 0;
}
}
if(clearZeroRow) {
for(int j=0; j < cols; ++j) {
M[0][j]= 0;
}
}
}
答案 28 :(得分:0)
好吧,我想出了一个使用4个bool和2个循环计数器的单通道,就地(非递归)解决方案。我没有设法将它减少到2个bool和2个int,但如果有可能的话我不会感到惊讶。它对每个单元执行大约3次读取和3次写入,并且它应该是O(N ^ 2)即。数组大小为线性。
我花了几个小时来解决这个问题 - 我不想在面试的压力下想出来!如果我做了一个booboo,我太累了,不能发现它...
嗯......我选择将“单次通过”定义为在矩阵中进行一次扫描,而不是每次触摸每个值! : - )
#include <stdio.h>
#include <memory.h>
#define SIZE 5
typedef unsigned char u8;
u8 g_Array[ SIZE ][ SIZE ];
void Dump()
{
for ( int nRow = 0; nRow < SIZE; ++nRow )
{
for ( int nColumn = 0; nColumn < SIZE; ++nColumn )
{
printf( "%d ", g_Array[ nRow ][ nColumn ] );
}
printf( "\n" );
}
}
void Process()
{
u8 fCarriedAlpha = true;
u8 fCarriedBeta = true;
for ( int nStep = 0; nStep < SIZE; ++nStep )
{
u8 fAlpha = (nStep > 0) ? g_Array[ nStep-1 ][ nStep ] : true;
u8 fBeta = (nStep > 0) ? g_Array[ nStep ][ nStep - 1 ] : true;
fAlpha &= g_Array[ nStep ][ nStep ];
fBeta &= g_Array[ nStep ][ nStep ];
g_Array[ nStep-1 ][ nStep ] = fCarriedBeta;
g_Array[ nStep ][ nStep-1 ] = fCarriedAlpha;
for ( int nScan = nStep + 1; nScan < SIZE; ++nScan )
{
fBeta &= g_Array[ nStep ][ nScan ];
if ( nStep > 0 )
{
g_Array[ nStep ][ nScan ] &= g_Array[ nStep-1 ][ nScan ];
g_Array[ nStep-1][ nScan ] = fCarriedBeta;
}
fAlpha &= g_Array[ nScan ][ nStep ];
if ( nStep > 0 )
{
g_Array[ nScan ][ nStep ] &= g_Array[ nScan ][ nStep-1 ];
g_Array[ nScan ][ nStep-1] = fCarriedAlpha;
}
}
g_Array[ nStep ][ nStep ] = fAlpha & fBeta;
for ( int nScan = nStep - 1; nScan >= 0; --nScan )
{
g_Array[ nScan ][ nStep ] &= fAlpha;
g_Array[ nStep ][ nScan ] &= fBeta;
}
fCarriedAlpha = fAlpha;
fCarriedBeta = fBeta;
}
}
int main()
{
memset( g_Array, 1, sizeof(g_Array) );
g_Array[0][1] = 0;
g_Array[0][4] = 0;
g_Array[1][0] = 0;
g_Array[1][4] = 0;
g_Array[3][1] = 0;
printf( "Input:\n" );
Dump();
Process();
printf( "\nOutput:\n" );
Dump();
return 0;
}
答案 29 :(得分:0)
创建结果矩阵并将所有值设置为1。 遇到0后立即查看数据矩阵,将结果矩阵行列设置为0
在第一遍结束时,结果矩阵将有正确的答案。
看起来很简单。有没有我缺少的技巧?你不被允许使用结果集吗?
编辑:
看起来像一个F#函数,但这有点作弊,因为即使你正在进行一次传递,该函数也可以是递归的。
看起来面试官正在试图弄清楚你是否了解函数式编程。
答案 30 :(得分:0)
虽然给定约束是不可能的,但最节省空间的方法是以重叠的交替行/列方式遍历矩阵,这将形成类似于以锯齿形方式铺设砖块的模式:
-----
|----
||---
|||--
||||-
使用它,你会按照指示进入每一行/每列,如果你在任何时候遇到0,设置一个布尔变量,然后重新遍历该行/列,将条目设置为0
这将不需要额外的内存,并且只使用一个布尔变量。不幸的是,如果将“far”边缘设置为全0,那么这是最糟糕的情况,你可以走完整个数组两次。