poj 2488 深搜+回溯

来源:互联网 发布:上财和复旦的差距 知乎 编辑:程序博客网 时间:2024/04/24 20:00
package com.liang.poj;import java.util.Scanner;public class Test2488 {static boolean b = true;public static void main(String[] args) {Scanner scan = new Scanner(System.in);int x = scan.nextInt();int y = scan.nextInt();int[][] chess = new int[x][y];boolean[][] visited = new boolean[x][y];int[][] ways = new int[x][y];if (x == 1 && y == 1) {b = false;System.out.println(0);}for (int i = 0; i < chess.length; i++) {for (int j = 0; j < chess[i].length; j++) {dfs(0, i, j, chess, visited, ways);}}if (b) {System.out.println("不存在这样的点");}}public static void dfs(int level, int x, int y, int[][] chess,boolean[][] visited, int[][] ways) {if (y > chess[0].length || x > chess.length) {return;}if (visited[x][y] == false) {ways[x][y] = level;visited[x][y] = true;}if (level == (chess.length*chess[0].length-1)) {b = false;show(ways);}for (int i = 0; i < chess.length; i++) {for (int j = 0; j < chess[i].length; j++) {if (j == y + 1 && i == x + 2 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y + 2 && i == x + 1 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y - 1 && i == x + 2 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y - 2 && i == x + 1 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y + 1 && i == x - 2 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y + 2 && i == x - 1 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y - 1 && i == x - 2 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}if (j == y - 2 && i == x - 1 && j <= chess[0].length&& i <= chess.length) {if (visited[i][j] == false) {dfs(level + 1, i, j, chess, visited, ways);visited[i][j] = false;}}}}}public static void show(int[][] ways) {for (int i = 0; i < ways.length; i++) {for (int j = 0; j < ways[i].length; j++) {System.out.print(ways[i][j] + "  ");}System.out.println();}}}


题目大意]:
给定一个p*q国际象棋棋盘,问马(骑士Knight)能否从某个点开始以跳马规则(横一步竖两步或横两步竖一步)将整个棋盘遍历;要求每个格子只能跳过一次,能的话,打印路线;
Sample Input:(先输入行,在输入列)

1 1

2 3

4 3

Sample Output:

0

不存在这样的点

0  7  2  (4 3的两种路线)
3  10  5 
6  1  8 
9  4  11 


0  11  2 
3  8  5 
6  1  10 
9  4  7 

原创粉丝点击