점(.)과 숫자가 있는 문자열이 있고 점은 셀이 비어 있음을 나타내고 임의의 셀에 숫자 x가 있으면 문자열 내에서 x 단계를 오른쪽이나 왼쪽으로 이동할 수 있음을 나타냅니다. 우리의 임무는 셀을 두 번 이상 방문할 수 있는지 여부를 확인하는 것입니다. 예를 들어 문자열이 ". 2 . . . 2 . ." 그러면 두 가지 다른 방법으로 4번째 셀을 방문할 수 있습니다. 두 번째 셀에서 오른쪽으로 두 단계 또는 셀 6에서 왼쪽으로 두 단계로 이동합니다.
문자열의 i번째 셀을 방문할 수 있는 횟수를 추적하기 위해 Visit[]라는 배열 하나를 사용합니다. 이제 문자열을 탐색하고 현재 문자가 점인지 숫자인지 확인합니다. 점의 경우 아무 것도 하지 않고 x의 경우 수를 늘리고 [i – x, i + x] 범위 내에서 방문한 배열의 방문 횟수를 1만큼 늘립니다. 한 번 이상.
예시
#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