- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Self Crossing in C++
Suppose we have an array x of n numbers. We start at point (0,0) and moves x[0] units to the north direction, then x[1] units to the west direction, x[2] units to the south direction , x[3] units to the east direction and so on. In other words, after each move our direction changes counter-clockwise. We have to devise an one-pass algorithm with O(1) extra space to determine whether our path crosses itself, or not.
So if the array is like − [3,4,2,5]
Answer will be true.
To solve this, we will follow these steps −
insert 0 at the index 4 of x
n := size of x, i := 4
for not initializing anything when i < n and x[i] > x[i - 2], increase i by 1 do −
Do nothing
if i is same as n, then, return false
if x[i] >= x[i - 2] - x[i - 4], then,
x[i - 1] = x[i - 1] - x[i - 3]
for increase i by 1, when i < n and x[i] < x[i - 2], increase i by 1 do −
Do nothing
return true when i is not same as n
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isSelfCrossing(vector<int>& x) { x.insert(x.begin(), 4, 0); int n = x.size(); int i = 4; for(; i < n && x[i] > x[ i - 2];i++); if(i == n) return false; if (x[i] >= x[i - 2] - x[i - 4]){ x[i - 1] -= x[i - 3]; } for (i++; i < n && x[i] < x[i - 2]; i++); return i != n; } }; main(){ Solution ob; vector<int> v = {3,4,2,5}; cout << (ob.isSelfCrossing(v)); }
Input
{3,4,2,5}
Output
1
- Related Articles
- Self Destructing Code in C
- C++ Program to find winner name of stick crossing game
- Count of Smaller Numbers After Self in C++
- self in Python class
- Self–invoking function in JavaScript?
- Self-Regulation in Health Behaviour
- The Cognitive Self
- The Social Self
- C++ Program to Implement self Balancing Binary Search Tree
- C++ Program to Perform Searching Using Self-Organizing Lists
- Create self-contained content in HTML5
- Concept of Self in Different Tradition
- Self-Assessment in Writing: Definition & Examples
- Identity and Self in Indian Thought
- CSS align-self property
