檢查C++字串中單元格是否可以被訪問多次


假設我們有一個包含點(.)和數字的字串,點表示單元格為空,如果任何單元格中存在數字x,則表示我們可以沿字串向右或向左移動x步。我們的任務是檢查我們是否可以多次訪問同一個單元格。

我們將使用一個名為visited[]的陣列來跟蹤字串第i個單元格可以被訪問的次數。現在遍歷字串,並檢查當前字元是點還是數字。對於點,什麼也不做;對於x,增加數字,並在visited陣列中[i – x, i + x]範圍內將訪問計數增加1。透過遍歷visited陣列,我們可以知道是否有任何單元格被訪問了多次。

示例

#include <iostream>
#include <queue>
using namespace std;
class Node {
   public:
   int key;
   Node *left, *right;
};
Node* getNode(int key) {
   Node* newNode = new Node;
   newNode->key = key;
   newNode->left = newNode->right = NULL;
   return newNode;
}
bool isLevelWiseSorted(Node* root) {
   int prevMax = INT_MIN;
   int min_val, max_val;
   int levelSize;
   queue<Node*> q;
   q.push(root);
   while (!q.empty()) {
      levelSize = q.size();
      min_val = INT_MAX;
      max_val = INT_MIN;
      while (levelSize > 0) {
         root = q.front();
         q.pop();
         levelSize--;
         min_val = min(min_val, root->key);
         max_val = max(max_val, root->key);
         if (root->left)
            q.push(root->left);
         if (root->right)
            q.push(root->right);
      }
      if (min_val <= prevMax)
         return false;
         prevMax = max_val;
   }
   return true;
}
int main() {
   Node* root = getNode(1);
   root->left = getNode(2);
   root->right = getNode(3);
   root->left->left = getNode(4);
   root->left->right = getNode(5);
   root->right->left = getNode(6);
   root->right->right = getNode(7);
   if (isLevelWiseSorted(root))
      cout << "Tree is levelwise Sorted";
   else
      cout << "Tree is Not levelwise sorted";
}

輸出

Tree is level wise Sorted

更新於: 2019年10月22日

122 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.