Sicily-1152 回溯算法

时间:2021-01-08 22:00:24

一.题意:

走日字,每个位置都有有8种新位置,从起点开始刚好过29步遍历其他位置一遍。

二.代码

 //
// main.cpp
// Sicily-1152 回溯算法
//
// Created by ashley on 14-10-21.
// Copyright (c) 2014年 ashley. All rights reserved.
// #include <iostream>
#include <utility>
using namespace std; //pair<int, int> moves[8] = {(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)};
int moveX[] = {, , , , -, -, -, -};
int moveY[] = {, , -, -, -, -, , };
bool isVisited[];
int path[];
int counter;
bool success;
typedef struct
{
int x;
int y;
}point;
void dfs(point startPoint)
{
if (counter == ) {
success = true;
cout << path[];
for (int i = ; i < ; i++) {
cout << " " << path[i];
}
cout << endl;
return;
}
for (int i = ; i < ; i++) {
point nextPoint = {startPoint.x + moveX[i], startPoint.y + moveY[i]};
int num = nextPoint.y * + nextPoint.x + ;
if (nextPoint.x < && nextPoint.x >= && nextPoint.y < && nextPoint.y >= && isVisited[num - ] == false) {
isVisited[num - ] = true;
path[counter] = num;
counter++;
if (success) {
return;
}
dfs(nextPoint);
isVisited[num - ] = false;
counter--;
}
}
}
int main(int argc, const char * argv[])
{
int source;
while (cin >> source) {
if (source == -) {
break;
}
point sourcePoint = {source % - , source / };
for (int i = ; i < ; i++) {
isVisited[i] = false;
}
success = false;
counter = ;
//源点只能走一次
isVisited[source - ] = true;
path[counter - ] = source;
dfs(sourcePoint);
}
return ;
}