马踏棋盘的基本过程:国际象棋的棋盘为8*8的方格棋盘。现将"马"放在任意指定的方格中,按照"马"走棋的规则将"马"进行移动。要求每个方格只能进入一次,最终使得"马"走遍棋盘的64个方格。
马踏棋盘的解决方案:基于深度优先搜索的方法是比较常用的算法,深度优先搜索算法也是数据结构中的经典算法之一,主要是采用递归的思想,一级一级的寻找,最后找到合适的解。
代码如下:
// App.javaimport java.awt.Color
import java.awt.Graphics
import java.awt.Rectangle
import javax.swing.JFrame
public class App extends JFrame {
public App() {
this.setTitle("Chess")
this.setSize(618, 647)
this.setLocationRelativeTo(null)
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
@Override
public void paint(Graphics g) {
super.paint(g)
Rectangle rect = getRootPane().getBounds()
int blockWidth = rect.width / 8
int blockHeight = rect.height / 8
for (int i = 0 i < 8 i++) {
for (int j = 0 j < 8 j++) {
if (i % 2 == 0) {
g.setColor(j % 2 == 0 ? Color.RED : Color.BLACK)
} else {
g.setColor(j % 2 == 0 ? Color.BLACK : Color.RED)
}
g.fillRect(rect.x + j * blockWidth, rect.y + i * blockHeight, blockWidth, blockHeight)
}
}
}
public static void main(String[] args) {
new App().setVisible(true)
}
}
运行结果: