兰顿蚂蚁,是于1986年,由克里斯·兰顿提出来的,属于细胞自动机的一种。
平面上的正方形格子被填上黑色或白色。在其中一格正方形内有一只“蚂蚁”。
蚂蚁的头部朝向为:上下左右其中一方。
蚂蚁的移动规则十分简单:
若蚂蚁在黑格,右转90度,将该格改为白格,并向前移一格;
若蚂蚁在白格,左转90度,将该格改为黑格,并向前移一格。
规则虽然简单,蚂蚁的行为却十分复杂。刚刚开始时留下的路线都会有接近对称,像是会重复,但不论起始状态如何,蚂蚁经过漫长的混乱活动后,会开辟出一条规则的“高速公路”。
蚂蚁的路线是很难事先预测的。
你的任务是根据初始状态,用计算机模拟兰顿蚂蚁在第n步行走后所处的位置。
接下来是 m 行数据。
每行数据为 n 个被空格分开的数字。0 表示白格,1 表示黑格。
接下来是一行数据:x y s k, 其中x y为整数,表示蚂蚁所在行号和列号(行号从上到下增长,列号从左到右增长,都是从0开始编号)。s 是一个大写字母,表示蚂蚁头的朝向,我们约定:上下左右分别用:UDLR表示。k 表示蚂蚁走的步数。
0 0 0 0 0 0
0 0 0 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
2 3 L 5
0 0 0
1 1 1
1 1 1
1 1 U 6
0 0
java解法:
import java.util.Scanner;
public class Demo_02 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int[][] array = new int[row + 1][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
array[i][j] = sc.nextInt();
}
}
int loctionX = sc.nextInt();
int loctionY = sc.nextInt();
String dirction = sc.next();
int step = sc.nextInt();
Ant ant = new Ant(loctionX, loctionY, dirction);
for (int i = 0; i < step; i++) {
changeDir(ant, array);
}
System.out.println(ant.x + " " + ant.y);
}
public static void changeDir(Ant ant, int[][] array){
if (array[ant.x][ant.y] == 0) {
dir(ant, 0, array);
}else{
dir(ant, 1, array);
}
}
public static void dir(Ant ant, int color, int[][] array){
int index = color == 1 ? 1 : -1;
String[] strs1;
if (color == 0) {
strs1 = new String[]{"L", "R", "D", "U"};
array[ant.x][ant.y] = 1;
}else{
strs1 = new String[]{"R", "L", "U", "D"};
array[ant.x][ant.y] = 0;
}
if (ant.str.equals("U")) {
ant.str = strs1[0];
ant.y += index;
}else if(ant.str.equals("D")){
ant.str = strs1[1];
ant.y -= index;
}else if (ant.str.equals("L")) {
ant.str = strs1[2];
ant.x -= index;
}else if (ant.str.equals("R")) {
ant.str = strs1[3];
ant.x += index;
}
}
}
class Ant{
int x = -1;
int y = -1;
String str = "";
public Ant(int x, int y , String str){
this.x = x;
this.y = y;
this.str = str;
}
}