Anonymous user
Knight's tour: Difference between revisions
→{{header|C++}}: Improved C++
(→{{header|Perl}}: minor cleanup) |
(→{{header|C++}}: Improved C++) |
||
Line 22:
#include <tuple>
#include <algorithm>
using namespace std;
template<int N = 8>
{
public:
array<pair<int, int>, 8> moves;
array<array<int, N>, N> data;
Board()
{
moves[0] = make_pair(2, 1);
moves[1] = make_pair(1, 2);
Line 41 ⟶ 43:
}
array<int, 8> sortMoves(
{
array<tuple<int, int>, 8> counts;
for
const int dx = get<0>(moves[i]);▼
int c = 0;
for
data[y2][x2] == 0)▼
if (x2 < 0
}
Line 61 ⟶ 70:
// Shuffle to randomly break ties
random_shuffle(counts.begin(), counts.end());
sort(counts.begin(), counts.end()); // Lexicographic sort▼
// Lexicographic sort
array<int, 8> out;
for
out[i] = get<1>(counts[i]);
return out;
}
void solve(
{
for (int v = 0; v < N; v++)▼
data[v][u] = 0;
data[y0][x0] = 1;
Line 82 ⟶ 94:
int n = 0;
while
{
const int x = get<0>(order[n]);▼
bool ok = false;
for
{
const int dx = moves[get<3>(order[n])[i]].first;▼
if
continue;
if(data[y + dy][x + dx] != 0)
continue;
data[y+dy][x+dx]
order[n] = make_tuple(x+dx,
▲ ok = true;
▲ break;
▲ }
}
if
{
data[y][x] = 0;
}
}
}
template<int N>
friend ostream& operator<<(ostream &out, const Board<N> &b);
};
template<int N>
ostream& operator<<(ostream &out, const Board<N> &b)
{
{
▲ if (u != 0)
for (int u = 0; u < N;
{
if (u != 0) out << ",";
out << setw(3) << b.data[v][u];
}
Line 126 ⟶ 145:
}
int main()
{
Board<5> b1;
b1.solve("c3");
|