zoukankan      html  css  js  c++  java
  • JAVA马的遍历

    题目描述

    在5*4的棋盘中,马只能走斜“日”字。马从位置(x, y)处出发,把棋盘的每一格都走一次,且只走一次,请找出所有路径。

    输入

    x,y,表示马的初始位置。

    输出

    将每一格都走一次的路径总数,如果不存在该路径则输出“No solution!”。

    样例输入 Copy

    1 1
    2 2

    样例输出 Copy

    32
    No solution!

    package book;
    
    import java.util.Scanner;
    
    
    public class Horse2{
    	static int[][] move = {{2,1},{2,-1},{1,2},{1,-2},{-1,-2},{-1,2},{-2,1},{-2,-1}};
    	static int vis[][]=new int[6][5];
    	static int dep=0,count=0;
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc = new Scanner(System.in);
    		while(sc.hasNext()){
    		int x=sc.nextInt();
    		int y=sc.nextInt();
    		vis[x][y]=1;
    		solve(x,y,2);
    		if(count==0) {
    			System.out.println("No solution!");
    		}
    		else 
    			{
    			System.out.println(count);count=0;dep=1;}
    		}
    	}
    	private static void solve(int x, int y, int dep) {
    		// TODO Auto-generated method stub
    		
    		for (int i = 0; i<=7; i++) {
    			int nx=x+move[i][0];
    			int ny=y+move[i][1];
    			if(check(nx,ny)){
    				vis[nx][ny]=dep;
    				if(dep==20){
    					count++;
    				}else
    					solve(nx,ny,dep+1);
    				    vis[nx][ny]=0;
    			}
    		}
    	}
    	private static boolean check(int xx, int yy) {
    
    	 return xx>=1&&xx<=5&&yy>=1&&yy<=4&&vis[xx][yy]==0;
    	}
    
    }
  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309592.html
Copyright © 2011-2022 走看看