题目链接:P1443
题目意思:就是在一个棋盘中,输出马到任何位置的最小步数即可
x,y表示坐标,n表示当前步数(个人认为BFS才是正解)
dfs代码:
package y2020_2_11;
import java.util.*;
public class P1443DFS {
static int a[][];
static boolean vis[][];
static int n;
static int m;
static int xx[] = new int[]{1,2,-2,-1,1,-2,-1,2};
static int yy[] = new int[]{2,1,-1,-2,-2,1,2,-1};
static void dfs(int x,int y,int count){
if(count > 200) // 阀值
return;
a[x][y] = count;
for(int i = 0;i < xx.length;i++)
if(x+xx[i]>=0 && x+xx[i]<n && y+yy[i]>=0 && y+yy[i]<m && (a[x+xx[i]][y+yy[i]] == -1 || a[x+xx[i]][y+yy[i]] > count+1))
dfs(x+xx[i],y+yy[i],count+1);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
a = new int[n][m];
vis = new boolean[n][m];
for(int i = 0;i < n;i++)
for(int j = 0;j < m;j++){
a[i][j] = -1;
vis[i][j] = false;
}
int sx = sc.nextInt();
int sy = sc.nextInt();
dfs(sx-1,sy-1,0);
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++)
System.out.printf("%-5d",a[i][j]);
System.out.println();
}
sc.close();
}
}
bfs代码
package y2020_2_11;
import java.util.*;
public class P1443BFS {
int n;
int m;
int sx;
int sy;
int xx[] = new int[]{1,2,-2,-1,1,-2,-1,2};
int yy[] = new int[]{2,1,-1,-2,-2,1,2,-1};
int map[][];
boolean vis[][];
Queue<Node> q = new LinkedList<Node>();
void bfs(){
while(!q.isEmpty()){
Node node = q.poll();
map[node.x][node.y] = node.n;// 走到了这个点 把步数给map数组
for(int i = 0;i < 8;i++)
if(node.x+xx[i]>=0 && node.x+xx[i]<n && node.y+yy[i]>=0&&node.y+yy[i]<m && !vis[node.x+xx[i]][node.y+yy[i]]){
vis[node.x+xx[i]][node.y+yy[i]] = true;
Node two = new Node(node.x+xx[i],node.y+yy[i],node.n+1);
q.add(two);
}
}
}
public static void main(String args[]){
P1443BFS nice = new P1443BFS();
Scanner sc = new Scanner(System.in);
nice.n = sc.nextInt();
nice.m = sc.nextInt();
nice.sx = sc.nextInt();
nice.sy = sc.nextInt();
nice.map = new int[nice.n][nice.m];
nice.vis = new boolean[nice.n][nice.m];
for(int i = 0;i < nice.n;i++)
for(int j = 0;j < nice.m;j++){
nice.map[i][j] = -1;
nice.vis[i][j] = false;
}
Node one = new Node(nice.sx-1,nice.sy-1,0);
nice.vis[nice.sx-1][nice.sy-1] = true;
nice.q.add(one);
nice.bfs();
for(int i = 0;i < nice.n;i++){
for(int j = 0;j < nice.m;j++)
System.out.printf("%-5d",nice.map[i][j]);
System.out.println();
}
sc.close();
}
}
class Node{
int x;
int y;
int n;
Node(int x,int y,int n){
this.x = x;
this.y = y;
this.n = n;
}
}