蓝桥杯练习:兰顿蚂蚁

本文介绍了蓝桥杯2014年第五届真题中的兰顿蚂蚁问题,提供了解题思路,主要涉及算法模拟的解决方法。
摘要由CSDN通过智能技术生成

问题 1429: [蓝桥杯][2014年第五届真题]兰顿蚂蚁

原题链接:问题 1429: [蓝桥杯][2014年第五届真题]兰顿蚂蚁
解题思路:进行模拟即可


import java.util.Scanner;

public class Main {
	static int m, n;//行,列
	static int x, y, k;//坐标,行走次数
	static String s;//头朝向
	static int[][] map;//存储图
	static String[] nowdir = { "L", "U", "R", "D" };//左上右下,+1右转-1左转
	static int[][] chageDir = { { 0, -1 }, { -1, 0 }, { 0, 1 }, { 1, 0 } };// 对应坐标改变

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		m = sc.nextInt();
		n = sc.nextInt();
		map = new int[m][n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				map[i][j] = sc.nextInt();
			}
		}
		x = sc.nextInt();
		y = sc.nextInt();
		s = sc.next();
		k = sc.nextInt();
		Ant ant = new Ant(x, y, s);
		dfs(ant);
		System.out.println(ant.x + " " + ant.y);
		sc.close();
	}

	private static void dfs(Ant ant) {
		if(k==0) {
			return;
		}
		run(ant);
		k-=1;
		dfs(ant);

	}

	private static void run(Ant ant) {
		if (map[ant.x][ant.y] == 1) {// 黑格右转变白格前进一格
			int j = 0;
			for (int i = 0; i < 4; i++) {
				if (ant.dir.equals(nowdir[i])) {
					if (i == 3) {
						j = 0;
						ant.dir = nowdir[j];
					} else {
						j = i + 1;
						ant.dir = nowdir[j];
					}
					break;
				}
			}
			map[ant.x][ant.y] = 0;
			ant.go(chageDir[j]);
		} else if (map[ant.x][ant.y] == 0) {// 白格左转变黑前进一格
			int j = 0;
			for (int i = 0; i < 4; i++) {
				if (ant.dir.equals(nowdir[i])) {
					if (i == 0) {
						j = 3;
						ant.dir = nowdir[j];
					} else {
						j = i - 1;
						ant.dir = nowdir[j];
					}
					break;
				}
			}
			map[ant.x][ant.y] = 1;
			ant.go(chageDir[j]);
		}

	}

	static class Ant {//内部类蚂蚁类,记录当前坐标与朝向
		int x;
		int y;
		String dir;

		public Ant(int x, int y, String dir) {
			this.x = x;
			this.y = y;
			this.dir = dir;
		}

		public void go(int[] Go) {//前进时坐标的改变
			this.x += Go[0];
			this.y += Go[1];
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值