C ++のブール行列の質問?
ここでは、1つの興味深いブール行列の問題が表示されます。 0と1を含む1つのブール行列が与えられます。私たちの目標は、1がマークされている場所を見つけることです。位置mat[i、j]で1がマークされている場合、行iと列jの1にすべてのエントリを作成します。例を見てみましょう。行列が以下のような場合-
1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0
その後、変更後は-
になります1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1
アルゴリズム
matrixUpdate(matrix [R、C])
begin define two matrices row[R] and col[C], and fill them with 0 mark the row and column indices of mat[R,C] where 1 is placed into the row[R] and col[C] matrices check row[R] and col[C] if the place is marked, then fill all places of that row and column with 1’s. end
例
#include <iostream>
#define R 4
#define C 4
using namespace std;
void updateMatrix(bool mat[R][C]) {
bool row[R];
bool col[C];
int i, j;
for (int i = 0; i < R; i++) { //set all elements of row matrix as 0
row[i] = 0;}
for (i = 0; i < C; i++) { //set all elements of col matrix as 0
col[i] = 0;}
for (int i = 0; i < R; i++) { //mark row and col matrix to identify where 1 is present
for (int j = 0; j < C; j++) {
if (mat[i][j] == 1) {
row[i] = 1;
col[j] = 1;
}
}
}
for (i = 0; i < R; i++) { //set all 1s to the row and col, where 1 is marked
for (j = 0; j < C; j++) {
if ( row[i] == 1 || col[j] == 1 ) {
mat[i][j] = 1;
}
}
}
}
void displayMatrix(bool mat[R][C]) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cout << mat[i][j];
}
cout << endl;
}
}
main() {
bool mat[R][C] = { {1, 0, 0, 1},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 1, 0, 0}
};
cout << "Given Matrix" << endl;
displayMatrix(mat);
updateMatrix(mat);
cout << "Updated Matrix" << endl;
displayMatrix(mat);
} 出力
Given Matrix 1001 0000 0000 0100 Updated Matrix 1111 1101 1101 1111
-
C++での行列の行方向と列方向のトラバーサル
マトリックスは2つの方法でトラバースできます。行マイズトラバーサルは、最初の行から2番目、というように最後の行まで、各行を1つずつ訪問します。行の要素は、インデックス0から最後のインデックスまで返されます。 列ごとのトラバーサルでは、要素は最初の列から最後の列に順番にトラバースされます。 2DマトリックスではM[i][j]。インデックスiは行を表すために使用され、インデックスjは列を表すために使用されます。行ごとのトラバーサルの場合は、から開始します。 i=0行目および0<=j<最後のインデックス i=1行目および0<=j<最後のインデックス ..... i=最後の行と0<=j<
-
C++のスパイラルマトリックスIII
R行とC列の2次元グリッドがあるとすると、東向きの(r0、c0)から開始します。ここで、グリッドの北西の角は最初の行と列にあり、グリッドの南東の角は最後の行と列にあります。このグリッドのすべての位置を訪問するために、時計回りのスパイラル形状で歩きます。グリッドの境界の外側にいるときは、グリッドの外側を歩き続けます(ただし、後でグリッドの境界に戻る場合があります)。グリッドの位置を表す座標のリストを、訪問した順序で見つける必要があります。したがって、グリッドが-のような場合 次に、矢印がパスになります。 これを解決するには、次の手順に従います- dirrを作成:=[[0,1]、[