P1443 马的遍历

题目链接: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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值