Skip to content

Instantly share code, notes, and snippets.

@iKrishneel
Created September 29, 2021 00:50
Show Gist options
  • Save iKrishneel/dd060068074c6e39eb085bce955fdac3 to your computer and use it in GitHub Desktop.
Save iKrishneel/dd060068074c6e39eb085bce955fdac3 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <string>
#include <bitset>
#include <algorithm>
#define BITS 4
using Matrix2D = std::vector<std::vector<int>>;
std::vector<int> to_binary(int i) {
auto bs = std::bitset<BITS>{i}.to_string();
std::vector<int> output;
for(auto c: bs) {
output.push_back(c == '1'? 1 : 0);
}
return output;
}
Matrix2D to_grid(const std::vector<int> &a) {
Matrix2D matrix;
for (auto i: a) {
matrix.push_back(to_binary(i));
}
return matrix;
}
int find_min_change(const Matrix2D &matrix, const int &i, const int &j, int cost = 0) {
if ((i < 0 || i + 1 > matrix[0].size()) || (j < 0 || j + 1 > matrix.size())) {
return cost;
}
if (matrix[j][i] == 0 && j == 0) {
return find_min_change(matrix, i + 1, j, cost);
}
if (matrix[j][i] == 0 && j < matrix.size() - 1) {
return BITS + 1;
}
int min_change = BITS + 1;
for (int k = -1; k <= 1; k++) {
auto x = k == 0 ? 0 : 1;
int a = find_min_change(matrix, i + k, j + 1, cost + x);
min_change = std::min(min_change, a);
}
return min_change;
}
int solution(const std::vector<int> & a) {
auto matrix = to_grid(a);
auto v = find_min_change(matrix, 0, 0, 0);
return v < matrix.size() ? v : -1;
}
int main() {
std::vector<int> A {7, 11, 10, 4};
auto r = solution(A);
std::cout << "Result: " << r << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment