นี่คือโจทย์เมทริกซ์บูลลีนน่าสนใจ มีเมทริกซ์บูลลีนที่ประกอบด้วย 0 และ 1 เป้าหมายคือหาตำแหน่งที่มี 1 หากมี 1 ที่ตำแหน่ง mat[i,j] เราจะทำให้ทุกค่าในแถว 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])
เริ่มต้น กำหนดอาร์เรย์ row[R] และ col[C] และเติม 0 ทำเครื่องหมายดัชนีแถวและคอลัมน์ที่มี 1 ในเมทริกซ์ mat[R,C] ลงใน row[R] และ col[C] ตรวจสอบ row[R] และ col[C] ถ้ามีเครื่องหมาย ให้เติม 1 ทุกตำแหน่งของแถวและคอลัมน์นั้น สิ้นสุด
ตัวอย่างโค้ด
#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++) {
row[i] = 0;
}
for (i = 0; i < C; i++) {
col[i] = 0;
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (mat[i][j] == 1) {
row[i] = 1;
col[j] = 1;
}
}
}
for (i = 0; i < R; i++) {
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;
}
}
int 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);
return 0;
}
ผลลัพธ์
Given Matrix 1001 0000 0000 0100 Updated Matrix 1111 1101 1101 1111