检查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 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告