Anonymous user
Solve a Numbrix puzzle: Difference between revisions
made more idiomatic, using vector in place of new array, etc
(Tcl implementation added) |
(made more idiomatic, using vector in place of new array, etc) |
||
Line 72:
#include <iostream>
#include <iterator>
#include <
#include <string
#include <bitset>
using namespace std;
typedef bitset<4> hood_t;
struct node
{
};
Line 87 ⟶ 88:
{
public:
{
if (puzz.size() < 1) return;
wid = max_wid;
hei = static_cast<int>(puzz.size()) / wid;
max = wid *
int len = max, c = 0;
arr = vector<node>(len, node({ 0, 0 }));
weHave = vector<bool>(len + 1, false);
for (const auto& s : puzz)
{
if (s == "*") { max--; arr[c++].val = -1; continue; }
arr[c].val = atoi(s.c_str());
if (arr[c].val > 0) weHave[arr[c].val] = true;
c++;
}
solveIt(); c =
for (auto&& s : puzz)
{
if (s == ".")
s = std::to_string(arr[c].val);
c++;
}
}
private:
{
if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true;
n.neighbors = getNeighbors(x, y);
if (weHave[w])
{
for (int d = 0; d < 4; d++)
{
if (n.neighbors[d])
{
int a = x + dx[d], b = y + dy[d];
if (arr[a + b * wid].val == w)
if (search(a, b, w + dr, dr))
return true;
}
}
return false;
}
for (int d = 0; d < 4; d++)
{
if (n.neighbors[d])
{
if (arr[a + b * wid].val == 0)
{
arr[a + b * wid].val = w;
if (search(a, b, w + dr, dr))
return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
hood_t getNeighbors(int x, int y)
{
hood_t retval;
for (int xx = 0; xx < 4; xx++)
{
int a =
if (a < 0
continue;
if (arr[a + b * wid].val > -1)
retval.set(xx);
}
return retval;
}
void solveIt()
{
int x, y, z;
if (z == 99999) { cout << "\nCan't find start point!\n"; return; }
search(x, y, z + 1, 1);
if (z > 1) search(x, y, z - 1, -1);
}
void findStart(int& x, int& y, int& z)
{
z = 99999;
for (int b = 0; b < hei; b++)
if (arr[a + wid * b].val > 0
{
x = a; y = b;
z = arr[a + wid * b].val;
}
}
vector<int> dx =
vector<int> dy = vector<int>({ 0, 0, -1, 1 });
int wid, hei, max;
vector<node> arr;
vector<bool> weHave;
};
//------------------------------------------------------------------------------
int main(
{
istringstream iss(p); vector<string> puzz;
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz));
nSolver s; s.solve(puzz, wid);
int c = 0;
for (const auto& s : puzz)
{
{
if (atoi(s.c_str()) < 10) cout << "0";
cout << s << " ";
}
else cout << " ";
if (++c >= wid) { cout << endl; c = 0; }
}
return system("pause");
}
</lang>
|