蓝桥杯-历届试题 兰顿蚂蚁

兰顿蚂蚁是于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


#include<stdio.h>
int a[100][100];
int x,y;
int k;//一共走K步 
int kk=0;


void panduan(int x,int y,char s){//判断左转还是右转 ,s为蚂蚁头朝向
	 kk=kk+1;
	 if(kk==k+1){
	 	printf("%d %d",x,y);
	 	return; 
	 } 
	 
	int flag;
	switch(s){
		case 'U':flag=0;break;//上 
		case 'L':flag=1;break;//左 
		case 'D':flag=2;break;//下 
		case 'R':flag=3;break;//右 
	}
	//左转:顺序上->左->下->右->上 
	if(a[x][y]==0){
		flag=(flag+1)%4;
		a[x][y]=1;
		
		if(flag==0){
			x=x-1;
			panduan(x,y,'U');
		}
		else if(flag==1){
			y=y-1;
			panduan(x,y,'L');
		}
		else if(flag==2){
			x=x+1;
			panduan(x,y,'D');
		}
		else if(flag==3){
			y=y+1;
			panduan(x,y,'R');
		} 
	}
		else{
			a[x][y]=0;
			
			if(flag==0)flag=3;
				else flag=(flag-1)%4;
			
			if(flag==0){
				x=x-1;
				panduan(x,y,'U');
			}
			else if(flag==1){
				y=y-1;
				panduan(x,y,'L');
			}
			else if(flag==2){
				x=x+1;
				panduan(x,y,'D');
			}
			else if(flag==3){
				y=y+1;
				panduan(x,y,'R');
			}
		} 
	 
}


int main(){
	int m,n,s;
	
	scanf("%d %d",&m,&n);
	for(int i=0;i<m;i++){
		for(int j=0;j<n;j++){
			scanf("%d",&a[i][j]);
		}
	}
	scanf("%d %d %c %d",&x,&y,&s,&k);
	
	panduan(x,y,s);
	
	
	return 0;
}



#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <cstdlib>
#include <string>
#include <string.h>
#include <math.h>

#include <stdio.h>

using namespace std;


int m,n; 
int x,y,k;
char s;
int dir;
char d[4]={'L','U','R','D'};
int a[120][120];


void moveforward(){
	if(d[dir]=='L'){y--;}
	if(d[dir]=='R'){y++;}
	if(d[dir]=='U'){x--;}
	if(d[dir]=='D'){x++;}
}

void turnleft(){
	dir=dir-1;
	if(dir<0)dir+=4;
}

void turnright(){
	dir=(dir+1)%4;
}


int main(){


	cin>>m>>n;
	
	for(int i=0;i<m;i++){
		for(int j=0;j<n;j++){
			cin>>a[i][j];
		}
	}
	cin>>x>>y;
	cin>>s>>k;
	for(int i=0;i<4;i++){
		if(s==d[i])dir=i;
	}
	for(int i=1;i<=k;i++){
		if(a[x][y]==0){
			turnleft();
			a[x][y]=1;
			moveforward();
		}else{
			turnright();
			a[x][y]=0;
			moveforward();
		}
		
		
	}
	cout<<x<<" "<<y;
	
	return 0;  
	
}

猜你喜欢

转载自blog.csdn.net/qq_34243930/article/details/79763833