1. 程式人生 > >騎士遊歷問題

騎士遊歷問題

source lin long line body boolean i++ start IT

由於最近在學習回溯法,所以跟回溯法相關的問題盡量都看下吧。
騎士遊歷問題的完整描述見:http://blog.csdn.net/sb___itfk/article/details/50905275

我的思路

我的實現如下,還是最簡單最粗暴的解法:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new
Solution(); long startTime = System.currentTimeMillis(); List<List<String>> res = s.traverse(5, 0, 0); int i = 1; for (List<String> item : res) { System.out.println("第 " + i + " 種走法:"); for (String line : item) { System.out
.println(line); } i++; } long endTime = System.currentTimeMillis(); System.out.println("運行耗時:" + (endTime - startTime) + " ms"); } public List<List<String>> traverse(int N, int sr, int sc) { int[][] board = new int[N][N]; board[sr][sc] = 1
; List<List<String>> res = new ArrayList<>(); dfs(board, sr, sc, res); return res; } private void dfs(int[][] board, int sr, int sc, List<List<String>> res) { if (check(board)) { List<String> lines = new ArrayList<>(); for (int i = 0; i < board.length; i++) { lines.add(Arrays.toString(board[i])); } res.add(lines); } int[] dr = {2, 2, -2, -2, 1, 1, -1, -1}; int[] dc = {1, -1, 1, -1, 2, -2, 2, -2}; for (int i = 0; i < 8; i++) { int[][] newBoard = deepthCopy(board); int cr = sr + dr[i]; int cc = sc + dc[i]; if (cr >= 0 && cr < board.length && cc >= 0 && cc < board.length && board[cr][cc] == 0) { newBoard[cr][cc] = newBoard[sr][sc] + 1; dfs(newBoard, cr, cc, res); } } } private int[][] deepthCopy(int[][] board) { int[][] res = new int[board.length][board.length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board.length; j++) { res[i][j] = board[i][j]; } } return res; } private boolean check(int[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board.length; j++) { if (board[i][j] == 0) { return false; } } } return true; } }

運行結果如下:

301 種走法:
[1, 16, 21, 6, 3]
[10, 5, 2, 15, 20]
[17, 22, 11, 4, 7]
[12, 9, 24, 19, 14]
[23, 18, 13, 8, 25]
第 302 種走法:
[1, 16, 11, 6, 3]
[10, 5, 2, 21, 12]
[15, 22, 17, 4, 7]
[18, 9, 24, 13, 20]
[23, 14, 19, 8, 25]
第 303 種走法:
[1, 16, 11, 6, 3]
[10, 5, 2, 17, 12]
[15, 22, 19, 4, 7]
[20, 9, 24, 13, 18]
[23, 14, 21, 8, 25]
第 304 種走法:
[1, 18, 11, 6, 3]
[10, 5, 2, 17, 12]
[19, 22, 13, 4, 7]
[14, 9, 24, 21, 16]
[23, 20, 15, 8, 25]
運行耗時:4073 ms

當 n = 5 時,運行時間已經上 4 秒了。。。可以雖然可以正確運行,但是效率並不 ok
那麽,還是去看看 sb___itfk 這位老鐵的解法吧:http://blog.csdn.net/sb___itfk/article/details/50905275

sb___itfk 解法

參考

http://blog.csdn.net/sb___itfk/article/details/50905275

騎士遊歷問題