更新矩阵

给定一个矩阵,大小为n x m ,元素为0和1.例如下图:

Given a matrix of size n x m filled with 0's and 1's
e.g.:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
如果矩阵在(i,j)处为1,将第i行和第j列用1填充。填充上图得到下图:
if the matrix has 1 at (i,j), fill the column j and row i with 1's
i.e., we get:
1 1 1 1 1
1 1 1 1 0
1 1 1 1 1
1 1 1 1 1
要求时间复杂度为O(n*m),空间复杂度为O(1)。
complexity: O(n*m) time and O(1) space
NOTE: you are not allowed to store anything except
'0' or '1' in the matrix entries


假设matrix从0开始,第一个元素为mat[0][0]

1.使用第一行和第一列作为作为表头,单独去保存行和列的信息。

2.如果元素mat[0][0]为1,需要在最后特殊处理。

3.从矩阵内部从下标为[1][1]的元素开始扫描直到最后一个元素。

4.如果元素在[row][col] == 1 ,更新表头的数据如下:mat[row][0] = 1;mat[0][col] = 1
5.再次扫描内部矩阵从下标[1][1]开始,如果对应表头的行或者列为1,将其设为1.

此时处理完所有矩阵内部的元素了,接下来处理表头的元素。


如果matt[0][0] == 1 将第一行和第一列全设为1.

完毕。

时间复杂度为O(2*(n-1)(m-1)+(n+m-2)) O(2*n*m)  Space O(1)

Assuming matrix is 0-based, i.e. the first element is at mat[0][0]

1. Use the first row and first column as table headers to contain row and column info respectively.
1.1 Note the element at mat[0][0]. If it is 1, it will require special handling at the end (described later)
2. Now, start scanning the inner matrix from index[1][1] up to the last element
2.1 If the element at[row][col] == 1 then update the table header data as follows
Row: mat[row][0] = 1;
Column: mat[0][col] = 1;
At this point we have the complete info on which column and row should be set to 1
3. Again start scanning the inner matrix starting from mat[1][1] and set each element
to 1 if either the current row or column contains 1 in the table header:
if ( (mat[row][0] == 1) || (mat[0][col] == 1) ) then set mat[row][col] to 1.

At this point we have processed all the cells in the inner matrix and we are
yet to process the table header itself
4. Process the table header
If the matt[0][0] == 1 then set all the elements in the first column and first
row to 1
5. Done

Time complexity O(2*((n-1)(m-1)+(n+m-1)), i.e. O(2*n*m - (n+m) + 1), i.e. O(2*n*m)
Space O(1)

#include <stdio.h>
static const int ROWS = 4;
static const int COLS = 5;
void print_array(int arr[][COLS],const int & ROWS,const int &COLS)
{
	for (int i = 0;i < ROWS;i++)
	{
		for (int j = 0;j<COLS;j++)
		{
			printf("%d\t",arr[i][j]);
		}
		printf("\n");
	}
}
void set_ones(int arr[][COLS],const int &ROWS,const int &COLS)
{
	
	//update table head
	for (int i = 1;i<ROWS;i++){
		for (int j = 1;j<COLS;j++)
			if (arr[i][j])
			{
				arr[0][j] = 1;
				arr[i][0] = 1;
			}
	}
	//update the inner table
	for (int i = 1;i<ROWS;i++){
		for (int j = 1;j<COLS;j++){
			if (arr[i][0]||arr[0][j])
				arr[i][j] = 1;
		}
	}
	//update 0 row and 0 column
	if (arr[0][0])
	{
		int i=ROWS-1,j=COLS-1;
		while(i)
			arr[i--][0] = 1;
		while (j)
			arr[0][j--] = 1;
	}
	
}
int main()
{
	int arr[ROWS][COLS] = { 
		{1, 1, 0, 1, 0},
		{0, 0, 0, 0, 0,}, 
		{0, 1, 0, 0, 0,},
		{1, 0, 1, 1, 0,}
	};

	printf("Original matrix:\n");
	print_array(arr, ROWS, COLS);
	set_ones(arr, ROWS, COLS);
	printf("\n");
	print_array(arr, ROWS, COLS);
	return 0;
}




你可能感兴趣的:(更新矩阵)