首頁 >後端開發 >C++ >C++程式以找出將所有儲存格轉換為黑色所需的迭代次數

C++程式以找出將所有儲存格轉換為黑色所需的迭代次數

王林
王林轉載
2023-08-25 18:54:31962瀏覽

C++程式以找出將所有儲存格轉換為黑色所需的迭代次數

假設,我們有一個包含兩種類型單元格的網格;黑細胞和白血球。黑色單元格表示為“#”,白色單元格表示為“.”。網格以字串數組形式提供給我們。現在,我們必須執行以下操作。

  • 我們將每個白色單元格轉換為黑色單元格,並與黑色單元格共用一側。我們執行此操作,直到網格的每個單元格都變成黑色。

  • 我們計算將網格的所有單元格轉換為黑色所需的迭代次數。一開始的網格必須包含一個黑色單元格。

因此,若輸入類似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 &#39;#&#39;, 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] == &#39;#&#39;) {
            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

以上是C++程式以找出將所有儲存格轉換為黑色所需的迭代次數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除