สมมติว่าเราได้รับตารางที่มีเซลล์สองประเภท เซลล์สีดำและเซลล์สีขาว เซลล์สีดำจะแสดงเป็น '#' และเซลล์สีขาวจะแสดงเป็น '.' กริดจะมอบให้เราในอาร์เรย์ของสตริง ตอนนี้ เราต้องดำเนินการดังต่อไปนี้
-
เราแปลงแต่ละเซลล์สีขาวเป็นสีดำที่มีด้านร่วมกับเซลล์สีดำ เราดำเนินการนี้จนกว่าทุกเซลล์ของกริดจะเป็นสีดำ
-
เรานับจำนวนการวนซ้ำที่ใช้ในการแปลงเซลล์ทั้งหมดของตารางเป็นสีดำ ตารางที่จุดเริ่มต้นต้องมีเซลล์สีดำหนึ่งช่อง
ดังนั้น หากอินพุตเป็น h =4, w =4, grid ={"#...", ".#.." , "....", "...#"}
| # | |||
| # | |||
| # |
แล้วผลลัพธ์จะเป็น 3
ต้องทำซ้ำ 3 ครั้งจึงจะแปลงเซลล์ทั้งหมดเป็นสีดำ
ขั้นตอน
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
Define an array dx of size: 4 containing := { 1, 0, - 1, 0 }
Define an array dy of size: 4 containing := { 0, 1, 0, - 1 }
Define one 2D array distance
Define one queue q that contain integer pairs
for initialize i := 0, when i < h, update (increase i by 1), do:
for initialize j := 0, when j < w, update (increase j by 1), do:
if grid[i, j] is same as '#', then:
distance[i, j] := 0
insert one pair(i, j) into q
while (not q is empty), do:
first element of auto now = q
delete element from q
for initialize dir := 0, when dir < 4, update (increase dir by 1), do:
cx := first value of now + dx[dir]
cy := second value of now + dy[dir]
if cx < 0 or cx >= h or cy < 0 or cy >= w, then:
if distance[cx, cy] is same as -1, then:
distance[cx, cy] := distance[first value of now, second value of now] + 1
insert one pair (cx, cy) into q
ans := 0
for initialize i := 0, when i < h, update (increase i by 1), do:
for initialize j := 0, when j < w, update (increase j by 1), do:
ans := maximum of ans and distance[i, j]
print(ans) ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <bits/stdc++.h>
using namespace std;
void solve(int h, int w, vector <string> grid){
int dx[4] = { 1, 0, -1, 0 };
int dy[4] = { 0, 1, 0, -1 };
vector<vector<int>> distance(h, vector<int>(w, -1));
queue<pair<int, int>> q;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (grid[i][j] == '#') {
distance[i][j] = 0;
q.push(pair<int, int>(i,j));
}
}
}
while (!q.empty()) {
auto now = q.front();
q.pop();
for (int dir = 0; dir < 4; dir++) {
int cx = now.first + dx[dir];
int cy = now.second + dy[dir];
if (cx < 0 || cx >= h || cy < 0 || cy >= w) continue;
if (distance[cx][cy] == -1) {
distance[cx][cy] = distance[now.first][now.second] + 1;
q.push(pair<int, int> (cx, cy));
}
}
}
int ans = 0; for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
ans = max(ans, distance[i][j]);
}
}
cout << ans << endl;
}
int main() {
int h = 4, w = 4; vector<string>
grid = {"#...", ".#.." , "....", "...#"};
solve(h, w, grid);
return 0;
} อินพุต
4, 4, {"#...", ".#.." , "....", "...#"} ผลลัพธ์
3