namespace 过河卒
{
class Program
{
const int RowsOFBoard = 20 , ColumnsOFboard = 20;
int X_Horse, Y_Horse, X_B, Y_B;
static int result = 0;
int[,] board = new int[RowsOFBoard, ColumnsOFboard];
void InitBoard() //根据马的位置初始化棋盘
{
board[X_Horse, Y_Horse] = 1;
board[X_B, Y_B] = 5;
for(int factor=-1;factor<3;factor+=2)
{
if (LegalJudge(X_Horse + factor * 1, Y_Horse + factor * 2))
board[X_Horse + factor * 1, Y_Horse + factor * 2] = 1;
if (LegalJudge(X_Horse + factor * 2, Y_Horse + factor * 1))
board[X_Horse + factor * 2, Y_Horse + factor * 1] = 1;
if (LegalJudge(X_Horse + factor * 1, Y_Horse + factor * -2))
board[X_Horse + factor * 1, Y_Horse + factor * -2] = 1;
if (LegalJudge(X_Horse + factor * 2, Y_Horse + factor * -1))
board[X_Horse + factor * 2, Y_Horse + factor * -1] = 1;
}
}
bool LegalJudge(int x,int y)
{
return x >= 0 && y >= 0 &&x<RowsOFBoard && y<ColumnsOFboard;
}
bool QuickJudge_Row(int x, int y)
{
return x <= X_B && board[x, y] != 1;
}
bool QuickJudge_Column(int x, int y)
{
return y <= Y_B && board[x, y] != 1;
}
void DFS(int x,int y)
{
if (x + 1 == X_B && y == Y_B)
{
result++;
return;
}
else
{
if(QuickJudge_Row(x+1,y))
DFS(x + 1, y);
}
if (x == X_B && y == Y_B)
{
result++;
return;
}
else
{
if (QuickJudge_Column(x , y+1))
DFS(x, y+1);
}
}
//输出棋盘,测试用
void CW()
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int t = 0; t < board.GetLength(1); t++)
Console.Write(board[i, t]+" ");
Console.WriteLine("");
}
}
static void Main(string[] args)
{
Program program = new Program();
//Console.WriteLine("请分别输入马和B的坐标");
string[] text = Console.ReadLine().Split(' ');
program.X_Horse = Int32.Parse(text[2]);
program.Y_Horse = Int32.Parse(text[3]);
program.X_B = Int32.Parse(text[0]);
program.Y_B = Int32.Parse(text[1]);
program.InitBoard();
// program.CW();
program.DFS(0, 0);
Console.WriteLine(result);
}
}
}
测试时B的坐标一旦大起来(十几)确实会耗时过多
比如:
15 17 5 8
119833848
DateTime costed is: 8183.4199ms
hxd们,瓶颈在哪里?