C++程式查詢網格中是否存在模式


假設,我們給定一個n * n維度的網格。我們必須檢測網格中是否存在交叉圖案,如下所示:

#...#
.#.#.
..#..
.#.#.
#...#

網格只能包含“#”和“.”。我們必須檢測模式並找出網格中存在多少種此類模式。網格和維度作為輸入提供給我們。

問題類別

程式設計中的各種問題可以透過不同的技術來解決。要解決問題,我們必須首先設計一個演算法,為此,我們必須詳細研究特定問題。如果同一問題反覆出現,則可以使用遞迴方法;或者,我們也可以使用迭代結構。if-else 和 switch case 等控制語句可用於控制程式中邏輯的流程。有效使用變數和資料結構提供了更簡單的解決方案以及輕量級、低記憶體需求的程式。我們必須檢視現有的程式設計技術,例如分治法、貪心演算法、動態規劃,並找出是否可以使用它們。這個問題可以透過一些基本邏輯或蠻力方法來解決。請遵循以下內容以更好地理解該方法。

因此,如果我們問題的輸入類似於 n = 5,並且網格為:

#...#
.#.#.
..#..
.#.#.
#...#,

則輸出將為 1。

步驟

為了解決這個問題,我們將遵循以下步驟:

count := 0
for initialize i := 1, when i < n - 1, update (increase i by 1), do:
   for initialize j := 1, when j < n - 1, update (increase j by 1), do:
      if grid[i, j] is same as '#' and grid[i - 1, j - 1] is same as '#' and grid[i - 1, j + 1] is same as '#' and grid[i + 1, j - 1] is same as '#' and grid[i + 1, j + 1] is same as '#', then:
         (increase count by 1)
print(count)

示例

讓我們看一下以下實現以獲得更好的理解:

#include<bits/stdc++.h>
using namespace std;
void solve(int n, vector<string> grid) {
   int count = 0;
   for(int i = 1; i < n - 1; i++){
      for(int j = 1; j < n - 1; j++){
         if(grid[i][j] == '#' && grid[i - 1][j - 1] == '#' && grid[i - 1][j + 1] == '#' && grid[i + 1][j - 1] == '#' && grid[i + 1][j + 1] == '#')
            count++;
      }
   }
   cout<< count;
}
int main() {
   int n = 5;
   vector<string> grid = {"#...#", ".#.#.", "..#..", ".#.#.", "#...#"};
   solve(n, grid);
   return 0;
}

輸入

5, {"#...#", ".#.#.", "..#..", ".#.#.", "#...#"}

輸出

1

更新於: 2022年4月7日

285 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告