teleren/devto huggingface dataset:
1579. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:27:49

```
class UnionFind{
    vector<int> id;
    int size;
public:
    UnionFind(int N ): id(N), size(N) {
        iota(begin(id), end(id), 0);
    }
    int find(int a) {
        return id[a] == a ? a : (id[a] = find(id[a]));
    }
    int connected(int a, int b) {
        return find(a) == find(b);
    }
    void connect(int a, int b) {
        int p = find(a), q = find(b);
        if (p == q) return;
        id[p] = q;
        --size;
    }
    int getSize() { return size; }
};
class Solution {
public:
    int maxNumEdgesToRemove(int n, vector<vector<int>>& E) {
        UnionFind a(n), b(n);
        int ans = 0;
        for (auto &e : E) {
            if (e[0] != 3) continue;
            int u = e[1] - 1, v = e[2] - 1;
            if (a.connected(u, v)) {
                ++ans;
                continue;
            }
            a.connect(u, v);
            b.connect(u, v);
        }
        for (auto &e : E) {
            int u = e[1] - 1, v = e[2] - 1;
            if (e[0] == 1) {
                if (a.connected(u, v)) ++ans;
                else a.connect(u, v);
            } else if (e[0] == 2) {
                if (b.connected(u, v)) ++ans;
                else b.connect(u, v);
            }
        }
        return a.getSize() != 1 || b.getSize() != 1 ? -1 : ans;
    }
};
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/
1547. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:26:27

```
class Solution {
 public:
  int minCost(int n, vector<int>& cuts) {
    cuts.push_back(0);
    cuts.push_back(n);
    sort(begin(cuts), end(cuts));

    // dp[i][j] := minCost(cuts[i..j])
    dp.resize(cuts.size(), vector<int>(cuts.size()));
    return minCost(cuts, 0, cuts.size() - 1);
  }

 private:
  vector<vector<int>> dp;

  int minCost(const vector<int>& cuts, int i, int j) {
    if (j - i <= 1)
      return 0;
    if (dp[i][j])
      return dp[i][j];

    dp[i][j] = INT_MAX;

    for (int k = i + 1; k < j; ++k)
      dp[i][j] = min(dp[i][j], cuts[j] - cuts[i] + minCost(cuts, i, k) +
                                   minCost(cuts, k, j));

    return dp[i][j];
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-cost-to-cut-a-stick/
1542. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:24:57

```
class Solution {
 public:
  int longestAwesome(string s) {
    int ans = 0;
    int prefix = 0;  // binary prefix
    vector<int> prefixToIndex(1024, s.length());
    prefixToIndex[0] = -1;

    for (int i = 0; i < s.length(); ++i) {
      prefix ^= 1 << s[i] - '0';
      ans = max(ans, i - prefixToIndex[prefix]);
      for (int j = 0; j < 10; ++j)
        ans = max(ans, i - prefixToIndex[prefix ^ 1 << j]);
      prefixToIndex[prefix] = min(prefixToIndex[prefix], i);
    }

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/find-longest-awesome-substring/submissions/
1531. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:22:10

```
class Solution {
 public:
  int getLengthOfOptimalCompression(string s, int k) {
    // dp[i][k] := length of optimal compression of s[i:] w/ at most k deletion
    dp.resize(s.length(), vector<int>(k + 1, kMax));
    return compression(s, 0, k);
  }

 private:
  constexpr static int kMax = 101;
  vector<vector<int>> dp;

  int compression(const string& s, int i, int k) {
    if (k < 0)
      return kMax;
    if (i == s.length() || s.length() - i <= k)
      return 0;
    if (dp[i][k] != kMax)
      return dp[i][k];

    int maxFreq = 0;  // max freq in s[i..j]
    vector<int> count(128);

    // make chars in s[i..j] be same
    // keep the char that has max freq in this range and remove other chars
    for (int j = i; j < s.length(); ++j) {
      maxFreq = max(maxFreq, ++count[s[j]]);
      dp[i][k] = min(dp[i][k],
                     getLength(maxFreq) +
                     compression(s, j + 1, k - (j - i + 1 - maxFreq)));
    }

    return dp[i][k];
  }

  int getLength(int maxFreq) {  // the length to compress `maxFreq`
    if (maxFreq == 1)
      return 1;  // c
    if (maxFreq < 10)
      return 2;  // [1-9]c
    if (maxFreq < 100)
      return 3;  // [1-9][0-9]c
    return 4;    // [1-9][0-9][0-9]c
  }
};

```


#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/string-compression-ii/
1526. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:20:54

```
class Solution {
 public:
  int minNumberOperations(vector<int>& target) {
    int ans = target.front();

    for (int i = 1; i < target.size(); ++i)
      if (target[i] > target[i - 1])
        ans += target[i] - target[i - 1];

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/
1521. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:19:37

```
class Solution {
 public:
  int closestToTarget(vector<int>& arr, int target) {
    int ans = INT_MAX;
    // s(j) := arr[i] & arr[i + 1] & ... & arr[j] for all 0 <= i <= j (fixed)
    unordered_set<int> s;

    for (const int a : arr) {
      unordered_set<int> s2{a};
      for (const int b : s)
        s2.insert(a & b);
      for (const int c : s = s2)
        ans = min(ans, abs(c - target));
    }

    return ans;
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target/
1505. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:15:34

```
class FenwickTree {
 public:
  FenwickTree(int n) : sums(n + 1) {}

  void update(int i, int delta) {
    while (i < sums.size()) {
      sums[i] += delta;
      i += i & -i;
    }
  }

  int get(int i) {
    int sum = 0;
    while (i > 0) {
      sum += sums[i];
      i -= i & -i;
    }
    return sum;
  }

 private:
  vector<int> sums;
};

class Solution {
 public:
  string minInteger(string num, int k) {
    const int n = num.length();
    string ans;
    FenwickTree tree(n);
    vector<bool> used(n);
    vector<queue<int>> numToIndices(10);

    for (int i = 0; i < n; ++i)
      numToIndices[num[i] - '0'].push(i);

    while (k > 0 && ans.length() < n)
      for (int d = 0; d < 10; ++d) {
        if (numToIndices[d].empty())
          continue;
        const int i = numToIndices[d].front();
        const int cost = i - tree.get(i);  // note the offset 1 in FenwickTree
        if (cost > k)
          continue;
        k -= cost;
        ans += '0' + d;
        used[i] = true;
        tree.update(i + 1, 1);
        numToIndices[d].pop();
        break;  // scan from 0 -> 9 again
      }

    for (int i = 0; i < n; ++i)
      if (!used[i])
        ans += num[i];

    return ans;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/
1520. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:18:10

```
class Solution {
 public:
  vector<string> maxNumOfSubstrings(string s) {
    const int n = s.length();
    vector<string> ans;
    vector<int> leftmost(26, n);    // leftmost index of each letter
    vector<int> rightmost(26, -1);  // rightmost index of each letter

    for (int i = 0; i < n; ++i) {
      leftmost[s[i] - 'a'] = min(leftmost[s[i] - 'a'], i);
      rightmost[s[i] - 'a'] = i;
    }

    auto getNewRight = [&](int i) {
      int right = rightmost[s[i] - 'a'];
      for (int j = i; j <= right; ++j) {
        if (leftmost[s[j] - 'a'] < i)  // find a letter's first index < i
          return -1;
        right = max(right, rightmost[s[j] - 'a']);  // right expands dynamically
      }
      return right;
    };

    int right = -1;  // last substring's rightmost index
    for (int i = 0; i < n; ++i) {
      if (i == leftmost[s[i] - 'a']) {  // current index is the first appearance
        const int newRight = getNewRight(i);
        if (newRight == -1)
          continue;  // find a letter's first index < i
        if (i <= right && !ans.empty())
          ans.back() = s.substr(i, newRight - i + 1);
        else
          ans.push_back(s.substr(i, newRight - i + 1));
        right = newRight;
      }
    }

    return ans;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/
1515. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:17:06

```
class Solution {
    double dist(vector<int> &a, vector<double> &b) {
        return sqrt(pow(a[0] - b[0], 2) + pow(a[1] - b[1], 2));
    }
    double all(vector<vector<int>> &A, vector<double> &p) {
        double ans = 0;
        for (auto &a : A) ans += dist(a, p);
        return ans;
    }
    const int dirs[4][2] = { {0,1},{0,-1},{-1,0},{1,0} };
public:
    double getMinDistSum(vector<vector<int>>& A) {
        double ans = DBL_MAX, step = 100, eps = 1e-6;
        vector<double> p(2, 0);
        while (step > eps) {
            bool found = false;
            for (auto &dir : dirs) {
                vector<double> next = {p[0] + step * dir[0], p[1] + step * dir[1]};
                double d = all(A, next);
                if (d < ans) {
                    ans = d;
                    p = next;
                    found = true;
                    break;
                }
            }
            if (!found) step /= 2;
        }
        return ans;
    }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/best-position-for-a-service-centre/
Empregabilidade, você está preparado para isso?
Tags: devrel, beginners, career
Published: 2022-07-06 14:16:23

Nos últimos dois anos migrei 2 vezes de carreira, migrei sem mudar de empresa e sem deixar de ser um desenvolvedor de software.

Mudar de carreira não necessariamente requer um novo título, títulos já não identificam o que realmente uma pessoa faz. Nós precisamos manter um olhar para o futuro e aceitar que nossos soft skills podem nos levar a executar tarefas que em alguns cargos ainda não conseguem ter uma boa definição. 

Hoje eu sou Desenvolvedor de Software, atuo como Developer Relations, e na minha pós-graduação me desenvolvo na área de comunicação, gestão de projetos e desenvolvimento de pessoas. 

Se eu me apresentar como desenvolvedor de software e falar o que realmente eu faço no meu dia a dia, as pessoas não vão entender qual é o meu trabalho, e isso não me preocupa, pois sei que 85% das profissões dos próximos 5 anos ainda nem existem.

> Melhor programa social é a empregabilidiade  -  Meu atual CEO Rodrigo Dantas

Isso não significa o fim das profissões que conhecemos hoje, mas quer dizer que elas certamente serão transformadas e nossas soft skills serão o principal fator de mudança.

A área que hoje você está atuando tem o objetivo X, e amanhã pode fazer sentido atuar no objetivo Y, e você precisa estar preparado para isso.

O processo de aprendizagem está mudando rapidamente e quem quer construir um processo transformador para empregabilidade deve ter como premissa: aprender a aprender, isso é, ser e ajudar pessoas a serem um tanto autodidatas. 

Se desafiar a compartilhar seus aprendizados irá permitir que você desenvolva um processo de troca e empatia. Rapidamente você será impactado e passará a desenvolver habilidades como raciocínio lógico e alta capacidade de autonomia e isso certamente ajudará você e a outros.

Acredito que cinco habilidades se mostram primordiais e que devemos incentivar e cultivar nas pessoas e em nós mesmos: 

1. Impulso criativo;
2. Lógica;
3. Inteligência emocional;
4. Julgamento;
5. Conhecimento tecnológico. 

A capacidade de desenvolver novas habilidades é incrivelmente útil em uma era de transformação como a que estamos vivendo. 

Muito do conteúdo necessário para nosso desenvolvimento já foi produzido e colocar mais pessoas em um mesmo ponto de partida é um propósito a ser alcançado.

O desafio passa a ser impulsionar pessoas para um processo autodidata, criar condições para acesso a ferramentas online e incluí-las em uma rede de contatos que favoreçam seu desenvolvimento.
1510. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:14:21

```
class Solution {
 public:
  bool winnerSquareGame(int n) {
    // dp[i] := the winning result for n = i
    vector<bool> dp(n + 1);

    for (int i = 1; i <= n; ++i)
      for (int j = 1; j * j <= i; ++j)
        if (!dp[i - j * j]) {  // remove j^2 stones make the opponent lose
          dp[i] = true;        // so we win
          break;
        }

    return dp[n];
  }
};

```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/stone-game-iv/
1499. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:12:28

```
class Solution {
 public:
  int findMaxValueOfEquation(vector<vector<int>>& points, int k) {
    int ans = INT_MIN;
    priority_queue<pair<int, int>> maxHeap;  // (y - x, x)

    for (const auto& p : points) {
      const int x = p[0];
      const int y = p[1];
      while (!maxHeap.empty() && x - maxHeap.top().second > k)
        maxHeap.pop();
      if (!maxHeap.empty())
        ans = max(ans, x + y + maxHeap.top().first);
      maxHeap.emplace(y - x, x);
    }

    return ans;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/max-value-of-equation/
1467. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:09:52

```
class Solution {
    double perm(vector<int> &A) {
        double ans = 1;
        for (int i = 0, j = 1; i < A.size(); ++i) {
            int n = A[i];
            for (int k = 1; k <= n; ++k, ++j) ans = ans * j / k; 
        }
        return ans;
    }
    int sum = 0;
    double dfs(vector<int> &A, vector<int>& a, vector<int> &b, int i, int sa, int sb) {
        if (sa > sum / 2 || sb > sum / 2) return 0; // invalid split because either `a` or `b` takes up more than half of the balls.
        if (i == A.size()) {
            int ca = 0, cb = 0;
            for (int i = 0; i < A.size(); ++i) ca += a[i] > 0;
            for (int i = 0; i < A.size(); ++i) cb += b[i] > 0;
            if (ca != cb) return 0; // invalid split because `a` and `b` don't have the same number of distinct colors.
            return perm(a) * perm(b);
        }
        double ans = 0;
        for (int j = 0; j <= A[i]; ++j) { // try different splits at the `i`-th element, i.e. a[i] + b[i] = A[i]`
            a[i] = j;
            b[i] = A[i] - j;
            ans += dfs(A, a, b, i + 1, sa + a[i], sb + b[i]);
        }
        a[i] = b[i] = 0;
        return ans;
    }
public:
    double getProbability(vector<int>& A) {
        sum = accumulate(begin(A), end(A), 0);
        vector<int> a(A.size()), b(A.size());
        return dfs(A, a, b, 0, 0, 0) / perm(A);
    }
};
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/
1458. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:08:28

```
class Solution {
public:
    int maxDotProduct(vector<int>& s, vector<int>& t) {
        int M = s.size(), N = t.size();
        vector<vector<int>> dp(M + 1, vector<int>(N + 1, INT_MIN));
        for (int i = 0; i < M; ++i) {
            for (int j = 0; j < N; ++j) {
                dp[i + 1][j + 1] = max({ max(0, dp[i][j]) + s[i] * t[j], dp[i + 1][j], dp[i][j + 1] });
            }
        }
        return dp[M][N];
    }
};
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/max-dot-product-of-two-subsequences/
1406. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:05:26

```
class Solution {
 public:
  string stoneGameIII(vector<int>& stoneValue) {
    // dp[i] := max "relative score" Alice can make w/ stoneValue[i:]
    dp.resize(stoneValue.size(), INT_MIN);

    const int score = stoneGameIII(stoneValue, 0);
    return score > 0 ? "Alice" : score < 0 ? "Bob" : "Tie";
  }

 private:
  vector<int> dp;

  int stoneGameIII(const vector<int>& stoneValue, int i) {
    if (i == stoneValue.size())
      return 0;
    if (dp[i] > INT_MIN)
      return dp[i];

    int sum = 0;
    for (int j = i; j < i + 3 && j < stoneValue.size(); ++j) {
      sum += stoneValue[j];
      dp[i] = max(dp[i], sum - stoneGameIII(stoneValue, j + 1));
    }

    return dp[i];
  };
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/stone-game-iii/
1220. Leetcode Solution in Java
Tags: java
Published: 2022-07-06 13:58:06

```
class Solution {
    public int countVowelPermutation(int n) {
        final int MODULO = 1000000007;
        long[][] dp = new long[n][5];
        Arrays.fill(dp[0], 1);
        for (int i = 1; i < n; i++) {
            dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % MODULO;
            dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % MODULO;
            dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % MODULO;
            dp[i][3] = dp[i - 1][2];
            dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % MODULO;
        }
        long sum = 0;
        for (int i = 0; i < 5; i++)
            sum += dp[n - 1][i];
        int count = (int) (sum % MODULO);
        return count;
    }
}
```
#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/count-vowels-permutation/
1377. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:03:09

```
class Solution {
 public:
  double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
    vector<vector<int>> graph(n + 1);
    queue<int> q{{1}};
    vector<bool> seen(n + 1);
    vector<double> prob(n + 1);

    seen[1] = true;
    prob[1] = 1.0;

    for (const auto& e : edges) {
      const int u = e[0];
      const int v = e[1];
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    while (!q.empty() && t-- > 0)
      for (int sz = q.size(); sz > 0; --sz) {
        const int a = q.front();
        q.pop();
        const int nChildren = count_if(begin(graph[a]), end(graph[a]),
                                       [&seen](int b) { return !seen[b]; });
        for (const int b : graph[a]) {
          if (seen[b])
            continue;
          seen[b] = true;
          prob[b] = prob[a] / nChildren;
          q.push(b);
        }
        if (nChildren > 0)
          prob[a] = 0.0;
      }

    return prob[target];
  }
};

```





#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/frog-position-after-t-seconds/
1373. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 14:01:50

```
struct T {
  bool isBST;
  int max;
  int min;
  int sum;
  T() : isBST(false) {}
  T(bool isBST, int max, int min, int sum)
      : isBST(isBST), max(max), min(min), sum(sum) {}
};

class Solution {
 public:
  int maxSumBST(TreeNode* root) {
    int ans = 0;
    traverse(root, ans);
    return ans;
  }

 private:
  T traverse(TreeNode* root, int& ans) {
    if (!root)
      return T(true, INT_MIN, INT_MAX, 0);

    T left = traverse(root->left, ans);
    T right = traverse(root->right, ans);

    if (!left.isBST || !right.isBST)
      return T();
    if (root->val <= left.max || root->val >= right.min)
      return T();

    // root is a valid BST
    const int sum = root->val + left.sum + right.sum;
    ans = max(ans, sum);
    return T(true, max(root->val, right.max), min(root->val, left.min), sum);
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/
1240. Leetcode Solution in Java
Tags: java
Published: 2022-07-06 13:59:39

```
class Solution {
    public int tilingRectangle(int n, int m) {
        int[][] dp = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (i == j)
                    dp[i][j] = 1;
                else {
                    dp[i][j] = Integer.MAX_VALUE;
                    int rowStart = 1, rowEnd = i / 2;
                    for (int row = rowStart; row <= rowEnd; row++)
                        dp[i][j] = Math.min(dp[i][j], dp[row][j] + dp[i - row][j]);
                    int columnStart = 1, columnEnd = j / 2;
                    for (int column = columnStart; column <= columnEnd; column++)
                        dp[i][j] = Math.min(dp[i][j], dp[i][column] + dp[i][j - column]);
                    for (int row = 1; row <= i; row++) {
                        for (int column = 1; column <= j; column++) {
                            for (int side = Math.min(row, column) - 1; side > 0; side--)
                                dp[i][j] = Math.min(dp[i][j], 1 + dp[row - side][column] + dp[i - row + side][column - side] + dp[i - row][j - column + side] + dp[row][j - column]);
                        }
                    }
                }
            }
        }
        return dp[n][m];
    }
}
```


#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/submissions/
1210. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-06 13:55:59

```
enum class Pos { HORIZONTAL, VERTICAL };

class Solution {
 public:
  int minimumMoves(vector<vector<int>>& grid) {
    const int n = grid.size();
    int ans = 0;
    // state of (x, y, pos)
    // pos := 0 (horizontal) / 1 (vertical)
    queue<tuple<int, int, Pos>> q{{{0, 0, Pos::HORIZONTAL}}};
    vector<vector<vector<bool>>> seen(n,
                                      vector<vector<bool>>(n, vector<bool>(2)));
    seen[0][0][static_cast<int>(Pos::HORIZONTAL)] = true;

    auto canMoveRight = [&](int x, int y, Pos pos) -> bool {
      if (pos == Pos::HORIZONTAL)
        return y + 2 < n && !grid[x][y + 2];
      return y + 1 < n && !grid[x][y + 1] && !grid[x + 1][y + 1];
    };

    auto canMoveDown = [&](int x, int y, Pos pos) -> bool {
      if (pos == Pos::VERTICAL)
        return x + 2 < n && !grid[x + 2][y];
      return x + 1 < n && !grid[x + 1][y] && !grid[x + 1][y + 1];
    };

    auto canRotateClockwise = [&](int x, int y, Pos pos) -> bool {
      return pos == Pos::HORIZONTAL && x + 1 < n && !grid[x + 1][y + 1] &&
             !grid[x + 1][y];
    };

    auto canRotateCounterclockwise = [&](int x, int y, Pos pos) -> bool {
      return pos == Pos::VERTICAL && y + 1 < n && !grid[x + 1][y + 1] &&
             !grid[x][y + 1];
    };

    while (!q.empty()) {
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [x, y, pos] = q.front();
        q.pop();
        if (x == n - 1 && y == n - 2 && pos == Pos::HORIZONTAL)
          return ans;
        if (canMoveRight(x, y, pos) && !seen[x][y + 1][static_cast<int>(pos)]) {
          q.emplace(x, y + 1, pos);
          seen[x][y + 1][static_cast<int>(pos)] = true;
        }
        if (canMoveDown(x, y, pos) && !seen[x + 1][y][static_cast<int>(pos)]) {
          q.emplace(x + 1, y, pos);
          seen[x + 1][y][static_cast<int>(pos)] = true;
        }
        const Pos newPos =
            pos == Pos::HORIZONTAL ? Pos::VERTICAL : Pos::HORIZONTAL;
        if ((canRotateClockwise(x, y, pos) ||
             canRotateCounterclockwise(x, y, pos)) &&
            !seen[x][y][static_cast<int>(newPos)]) {
          q.emplace(x, y, newPos);
          seen[x][y][static_cast<int>(newPos)] = true;
        }
      }
      ++ans;
    }

    return -1;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/