解题思路:

注意事项:

参考代码:

import java.util.Scanner;

public class Main {

        static String[] dir = {"U","R","D","L"};

        static int[] xincress = {-1,0,1,0};//方向递增数组和上面的 方向数组对应

        static int[] yincress = {0,1,0,-1};

        static int dirIndex;//方向数组的坐标 记录当前朝向

        static int x;

        static int y;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int m = sc.nextInt();//行

int n = sc.nextInt();//列

int[][] 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();

String towards = sc.next();//蚂蚁的朝向

int stepCount = sc.nextInt();//蚂蚁前进步数

for (int i = 0; i < 4; i++) {

if (dir[i].compareTo(towards) == 0) {

dirIndex = i;

break;

}

}


for (int i = 0; i < stepCount; i++) {

precede(map);

}

System.out.print(x +" ");

System.out.println(y);


}

//蚂蚁前进方法

public static void precede(int[][] map) {

//当前在黑格

if(map[x][y] == 1) {

map[x][y] = 0;//变为白格

dirIndex = (dirIndex + 1) % 4;

// System.out.print(dirIndex + "   ");

x = x + xincress[dirIndex];

y = y + yincress[dirIndex];

// System.out.println("向右往前一步 当前在" + x + " ---" + y);

return;

}


//当前在白格

if(map[x][y] == 0) {

map[x][y] = 1;//变为黑格

dirIndex = (dirIndex - 1 + 4) % 4;//避免越界 保证是最小正数

// System.out.print(dirIndex + "   ");

x = x + xincress[dirIndex];

y = y + yincress[dirIndex];

// System.out.println("向左往前一步 当前在" + x + " ---" + y);

    return;

}

}



}


 

0.0分

3 人评分

  评论区

  • «
  • »