问题 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];
}
}
}