Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int main() {
- vector<string> v;
- string s;
- while (getline(cin, s))
- v.push_back(s);
- int n = v.size(), m = v[0].size();
- int x = -1, y = -1;
- // Find initial position of '^'
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < m; ++j) {
- if (v[i][j] == '^') {
- x = i;
- y = j;
- break;
- }
- }
- }
- // Direction vectors
- string dir = "^>v<";
- vector<int> dirx = {-1, 0, 1, 0};
- vector<int> diry = {0, 1, 0, -1};
- auto is_valid = [&](int nx, int ny) {
- return nx >= 0 && nx < n && ny >= 0 && ny < m && v[nx][ny] != '#';
- };
- int count = 0;
- while (true) {
- bool moved = false;
- for (int k = 0; k < 4; ++k) {
- if (v[x][y] == dir[k]) {
- int nx = x + dirx[k], ny = y + diry[k];
- int nx2 = x + dirx[(k + 1) % 4] , ny2 = y + diry[(k + 1) % 4];
- int nx3 = x + dirx[(k + 2) % 4] , ny3 = y + diry[(k + 2) % 4];
- if (is_valid(nx, ny)) {
- v[x][y] = 'X'; // Mark current position as visited
- x = nx;
- y = ny;
- v[x][y] = dir[k];
- moved = true;
- break;
- }
- else if(nx == -1 or nx == n or ny == -1 or ny == m) {
- v[x][y] = 'X';
- break;
- }
- else if(is_valid(nx2 , ny2)) {
- v[x][y] = 'X';
- x = nx2;
- y = ny2;
- v[x][y] =dir[(k + 1) % 4];
- moved = true;
- break;
- }
- else if(nx2 == -1 or nx2 == n or ny2 == -1 or ny2 == m) {
- v[x][y] = 'X';
- break;
- }
- else if(is_valid(nx3 , ny3)) {
- v[x][y] = 'X';
- x = nx3;
- y = ny3;
- v[x][y] = dir[(k + 2) % 4];
- moved = true;
- break;
- }
- else if(nx3 == -1 or nx3 == n or ny3 == -1 or ny3 == m) {
- v[x][y] = 'X';
- break;
- }
- else break;
- }
- }
- if (!moved) break; // If no movement is possible, stop
- }
- // Count 'X' marks
- for (auto &row : v) {
- count += count_if(row.begin(), row.end(), [](char c) { return c == 'X'; });
- }
- cout << count << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment