兰顿蚂蚁,是于1986年,由克里斯·兰顿提出来的,属于细胞自动机的一种。
平面上的正方形格子被填上黑色或白色。在其中一格正方形内有一只“蚂蚁”。
蚂蚁的头部朝向为:上下左右其中一方。
蚂蚁的移动规则十分简单:
若蚂蚁在黑格,右转90度,将该格改为白格,并向前移一格;
若蚂蚁在白格,左转90度,将该格改为黑格,并向前移一格。
规则虽然简单,蚂蚁的行为却十分复杂。刚刚开始时留下的路线都会有接近对称,像是会重复,但不论起始状态如何,蚂蚁经过漫长的混乱活动后,会开辟出一条规则的“高速公路”。
蚂蚁的路线是很难事先预测的。
你的任务是根据初始状态,用计算机模拟兰顿蚂蚁在第n步行走后所处的位置。
输入格式
输入数据的第一行是 m n 两个整数(3 < m, n < 100),表示正方形格子的行数和列数。
接下来是 m 行数据。
每行数据为 n 个被空格分开的数字。0 表示白格,1 表示黑格。
接下来是一行数据:x y s k, 其中x y为整数,表示蚂蚁所在行号和列号(行号从上到下增长,列号从左到右增长,都是从0开始编号)。s 是一个大写字母,表示蚂蚁头的朝向,我们约定:上下左右分别用:UDLR表示。k 表示蚂蚁走的步数。
输出格式
输出数据为两个空格分开的整数 p q, 分别表示蚂蚁在k步后,所处格子的行号和列号。
样例输入
5 6
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
样例输出
1 3
样例输入
3 3
0 0 0
1 1 1
1 1 1
1 1 U 6
样例输出
0 0
思考:
1、上下左右四个方向分别对坐标的影响是?
向上移动:横坐标减1
向下移动:横坐标加1
向左移动:纵坐标减1
向右移动:纵坐标加1
注意点,坐标减一的过程中会出现负数,这样可以采取减一之后加上长度然后再对长度取余的方法。
2、经过旋转操作发现规律,定义方向数组String[] direction = new String[] {"U","R","D","L"},这时如果是白格的话, 方向数组下标递减就是旋转后的方向,如果是黑格的话,方向数组下标递增就是旋转后的方向。
代码如下
package yearlyExamination;
import java.util.Scanner;
public class Lx33_LantonAnt {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] direction = new String[] {"U","R","D","L"};
Scanner reader = new Scanner(System.in);
int m = reader.nextInt();
int n = reader.nextInt();
int[][] nArray = new int[m][n];
for(int i=0;i<m;i++)
{
for(int j =0;j<n;j++)
{
nArray[i][j] = reader.nextInt();
}
}
int x = reader.nextInt();
int y = reader.nextInt();
String s = reader.next();
int k = reader.nextInt();
int d = 0;//记录方向在数组中的下标
for(int i=0;i<4;i++)
{
if(direction[i].equals(s))
{
d = i;
}
}
//System.out.println("d "+direction[d]);
Ant ant = new Ant(x,y);
for(int i=0;i<k;i++)
{
//发现规律 如果是白格的话 方向数组下标递减就是旋转后的方向
//黑格时,方向数组下标递增就是旋转后的方向
//System.out.println("nArray[x][y]"+nArray[x][y]);
if(nArray[ant.x][ant.y] == 0)
{
nArray[ant.x][ant.y] = 1;
d = (d-1+4)%4;//得到旋转后的方向下标
s = direction[d];
goWalk(ant, s, m, n);//移动
}else {
nArray[ant.x][ant.y] = 0;
d = (d+1)%4;
s = direction[d];
goWalk(ant, s, m, n);
}
//System.out.println(ant.x + " " + ant.y);
}
System.out.println(ant.x+" " +ant.y);
}
public static void goWalk(Ant ant,String s,int m,int n) {
switch(s)
{
case "U":
ant.x = (ant.x-1+m)%m;
break;
case "L":
ant.y= (ant.y-1+n)%n;
break;
case "D":
ant.x = (ant.x+1)%m;
break;
case "R":
ant.y = (ant.y+1)%n;
break;
default:
break;
}
}
}
class Ant{
/**
* 蚂蚁坐标类,用于保存蚂蚁移动时的横纵坐标
*/
public int x;//横坐标
public int y;//纵坐标
public Ant(int x,int y)
{
this.x = x;
this.y = y;
}
}