筆試+刷題-圖論
阿新 • • 發佈:2018-12-10
qunar2019馬在8*8棋盤上從A到B最短需要幾步(DFS)
package com.qunar; import java.util.Scanner; public class Main21 { private static Scanner input =new Scanner(System.in); private static int x1=input.nextInt(); private static int y1=input.nextInt(); private static int x2=input.nextInt(); private static int y2=input.nextInt(); private static int res=Integer.MAX_VALUE; private static boolean[][] marked=new boolean[9][9]; private static int[][] dir=new int[][] {{1,2},{1,-2},{-1,2},{-1,-2}, {2,1},{2,-1},{-2,1},{-2,-1}}; public static void main(String[] args) { // TODO Auto-generated method stub int step=0; dfs(x1,y1,0); System.out.println(res); } private static void dfs(int x, int y,int step) { // TODO Auto-generated method stub if (step<res) { if(x==x2&&y==y2) { res=step; return; } else { for (int i=0;i<8;i++) { int tmpx=x+dir[i][0]; int tmpy=y+dir[i][1]; if(tmpx>=1&&tmpx<=8&&tmpy>=1&&tmpy<=8&&!marked[tmpx][tmpy]) { marked[tmpx][tmpy]=true; dfs(tmpx,tmpy,step+1); marked[tmpx][tmpy]=false; } } } } } }