1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| using System;
namespace 跳马 { class Horse { public int num { get; set; }
int x0, y0, cx, cy; int[,] dir = { { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 }, { -1, -2 }, { -2, -1 }, { -2, 1 }, { -1, 2 } }; int[,] path = new int[100, 2]; int[,] result = new int[20, 20];
public Horse(int x0, int y0, int cx, int cy) { path[0, 0] = this.x0 = x0; path[0, 1] = this.y0 = y0; this.cx = cx; this.cy = cy; num = 0; Move(x0, y0, 0, 1); }
void Move(int x, int y, int m, int step) { int x1, y1; for (int i = m; i < 8; i++) { int flag = 0;
x1 = x + dir[i, 0]; y1 = y + dir[i, 1];
if (x1 < 1 || x1 > cx || y1 < 1 || y1 > cy) { x1 -= dir[i, 0]; y1 -= dir[i, 1]; continue; }
for (int j = 1; j <= step; j++) { if (x1 == path[j, 0] && y1 == path[j, 1]) { flag = 1; break; } } if (flag == 1) { x1 -= dir[i, 0]; y1 -= dir[i, 1]; continue; }
path[step, 0] = x1; path[step, 1] = y1;
if (x1 == x0 && y1 == y0) { for (int j = 1; j <= step; j++) { if (path[j, 0] == 1 || path[j, 0] == cx || path[j, 1] == 1 || path[j, 1] == cy) { flag = 1; } }
if (flag == 1) { num++;
Console.Write("方案{0}:", num); for (int j = 0; j <= step; j++) { Console.Write("({0},{1})", path[j, 0], path[j, 1]); } Console.WriteLine();
path[step, 0] = 0; path[step, 1] = 0;
step--; i++;
Move(path[step,0], path[step,1], i, step + 1); } } else { Move(x1, y1, 1, step + 1); } } }
}
class Program { static void Main(string[] args) { int x0, y0, cx, cy;
Console.Write("请输入棋盘宽度(3≤cx≤20):"); cx = int.Parse(Console.ReadLine()); Console.Write("请输入棋盘长度(3≤cy≤20):"); cy = int.Parse(Console.ReadLine()); Console.Write("请输入起始位置(1≤x0≤cx):"); x0 = int.Parse(Console.ReadLine()); Console.Write("请输入起始位置(1≤y0≤cy):"); y0 = int.Parse(Console.ReadLine());
Horse horse = new Horse(x0, y0, cx, cy); Console.WriteLine("总方案数:{0}", horse.num);
Console.ReadKey(true); } } }
|