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

思路:

首先要确定蚂蚁的“坐标”,“头所在方位”,和所在格子的"颜色",然后根据其移动规则进行移动,根据所要移动的步数确定循环的次数哦b( ̄▽ ̄)d 

import java.util.*;

public class Main {
	static int[][] num;
	static String direction;

	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		int m = reader.nextInt();// 行数
		int n = reader.nextInt();// 列数

		num = new int[m][n];

		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				num[i][j] = reader.nextInt();// 给矩阵赋值
			}
		}
		int x = reader.nextInt();   //横坐标
		int y = reader.nextInt();   //纵坐标
		direction = reader.next();  //初始方向
		int step = reader.nextInt();//需要走的步骤

		remove(x, y, step);    //进行移动
	}

	private static void remove(int x, int y, int step) {
		// TODO Auto-generated method stub
		for (int i = 0; i < step; i++) {
			if (num[x][y] == 1) {// 黑格
				switch (direction) {
				case "U":
					direction = "R";//重设方向
					num[x][y] = 0;  //变为白格
					y += 1;         //位置移动
					break;
				case "D":
					direction = "L";
					num[x][y] = 0;
					y -= 1;
					break;
				case "L":
					direction = "U";
					num[x][y] = 0;
					x -= 1;
					break;
				case "R":
					direction = "D";
					num[x][y] = 0;
					x += 1;
					break;
				}
			} else {// 白格
				switch (direction) {
				case "U":
					direction = "L";//重设方向
					num[x][y] = 1;  //变为黑格
					y -= 1;         //移动位置
					break;
				case "D":
					direction = "R";
					num[x][y] = 1;
					y += 1;
					break;
				case "L":
					direction = "D";
					num[x][y] = 1;
					x += 1;
					break;
				case "R":
					direction = "U";
					num[x][y] = 1;
					x -= 1;
					break;
				}
			}
		}
		System.out.println(x + " " + y);  //所在位置输出
	}
}


猜你喜欢

转载自blog.csdn.net/sytandxly/article/details/79502669