ในปัญหานี้ เราได้รับเมทริกซ์ไบนารี NxN bin[][]. งานของเราคือหาขนาดของเครื่องหมาย '+' ที่ใหญ่ที่สุดที่ประกอบด้วย 1 ทั้งหมดในเมทริกซ์ไบนารี
มาดูตัวอย่างเพื่อเข้าใจปัญหา
Input
0 1 1 1 1 1 0 1 0
Output
5
วิธีแก้ปัญหา
วิธีแก้ที่ง่ายคือการหา '+' ที่ใหญ่ที่สุด ซึ่งเราต้องหาจำนวน 1 สูงสุดในหนึ่งทิศทางสำหรับจุดในเมทริกซ์ ซึ่งต้องเท่ากันในทั้งสี่ทิศทางสำหรับ 1 ที่กำหนด สำหรับนี้ เราจะสร้างเมทริกซ์หนึ่งสำหรับแต่ละด้านของจุด คือ 4 เมทริกซ์ แต่ละอันจะเก็บจำนวน 1 ติดต่อกันสำหรับองค์ประกอบที่กำหนด สำหรับค่าดัชนีทั้งหมด เราจะหาค่าสูงสุดซึ่งเป็นค่าต่ำสุดของ 1 ติดต่อกันในทั้งสี่ทิศทาง
โปรแกรมแสดงการทำงานของวิธีแก้
ตัวอย่าง
#include <iostream>
using namespace std;
#define N 7
int findLargestPlusSize(int mat[N][N]) {
int conOneLeft[N][N], conOneRight[N][N], conOneTop[N][N], conOneBottom[N][N];
for (int i = 0; i < N; i++) {
conOneTop[0][i] = mat[0][i];
conOneBottom[N - 1][i] = mat[N - 1][i];
conOneLeft[i][0] = mat[i][0];
conOneRight[i][N - 1] = mat[i][N - 1];
}
for (int i = 0; i < N; i++) {
for (int j = 1; j < N; j++) {
if (mat[i][j] == 1)
conOneLeft[i][j] = conOneLeft[i][j - 1] + 1;
else
conOneLeft[i][j] = 0;
if (mat[j][i] == 1)
conOneTop[j][i] = conOneTop[j - 1][i] + 1;
else
conOneTop[j][i] = 0;
j = N - 1 - j;
if (mat[j][i] == 1)
conOneBottom[j][i] = conOneBottom[j + 1][i] + 1;
else
conOneBottom[j][i] = 0;
if (mat[i][j] == 1)
conOneRight[i][j] = conOneRight[i][j + 1] + 1;
else
conOneRight[i][j] = 0;
j = N - 1 - j;
}
}
int maxConOne = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++){
int ConOnes = min(min(conOneTop[i][j], conOneBottom[i][j]), min(conOneLeft[i][j], conOneRight[i][j]));
if(ConOnes > maxConOne)
maxConOne = ConOnes;
}
}
if (maxConOne)
return (4 * (maxConOne - 1) + 1);
return 0;
}
int main() {
int mat[N][N] = {
{ 1, 0, 1, 1, 1, 1, 0 },
{ 1, 0, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0 },
{ 0, 0, 0, 0, 1, 0, 0 },
{ 1, 0, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1 },
{ 1, 0, 0, 0, 1, 0, 0 },
};
cout<<"The size of the largest plus formed by ones is "<<findLargestPlusSize(mat);
return 0;
}
ผลลัพธ์
The size of the largest plus formed by ones is 9