蘭頓螞蟻這題,是個模拟題,也可以是DFS。
關鍵注意兩點:
一、無論用String還是char[]來表示方向組,ULDR的順序不是随便亂寫的
二、是先轉向,再向前走,反過來就錯了
//這段代碼,系統提示有運作時錯誤......
//尚未發現是什麼原因,醉了,後面的測試資料也不讓看...
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n= sc.nextInt();
int[][] a = new int[m][n];
for (int i=;i<m;i++){
for (int j=;j<n;j++){
a[i][j] = sc.nextInt();
}
}
int x = sc.nextInt();
int y = sc.nextInt();
char s = sc.next().charAt();
int k = sc.nextInt();
char[] direction = {'U', 'R', 'D', 'L'};
int flag = ; //表示第幾個字元
for (int i=;i<direction.length;i++){
if (s == direction[i]){
flag = i;
}
}
for (int i=; i<k; i++){
if (a[x][y] == ){
a[x][y] = ;
flag = flag + ;
}else{
a[x][y] = ;
flag = flag - ;
}
s = direction[(flag+)%];
switch (s){
case 'L':
y--;
break;
case 'R':
y++;
break;
case 'U':
x--;
break;
case 'D':
x++;
break;
}
}
System.out.println(x +" " +y);
}
}
//AC代碼
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
char[] lz = { 'L', 'D', 'R', 'U' }; // 左轉方向數組
char[] rz = { 'L', 'U', 'R', 'D' }; // 右轉方向數組
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] maps = new int[n][m];
for (int i = ; i < n; i++)
for (int j = ; j < m; j++)
maps[i][j] = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
char s = in.next().trim().charAt();
int k = in.nextInt();
for (int j = , i = ; j < k; j++) {
if (maps[x][y] == ) { // 黑色格子 右轉90度
maps[x][y] = ; // 置為白色格子
for (i = ; i < ; i++)
if (rz[i] == s)
break;
s = rz[(i + ) % ];
switch (s) {
case 'L':
y--;
break;
case 'R':
y++;
break;
case 'U':
x--;
break;
case 'D':
x++;
break;
}
} else { // 白色格子 左轉90度
maps[x][y] = ; // 置為黑色格子
for (i = ; i < ; i++)
if (lz[i] == s)
break;
s = lz[(i + ) % ];
switch (s) {
case 'L':
y--;
break;
case 'R':
y++;
break;
case 'U':
x--;
break;
case 'D':
x++;
break;
}
}
}
System.out.println(x + " " + y);
}
}
//AC代碼
import java.util.*;
class Main
{
public static void main(String[] arge)
{
Scanner cin = new Scanner(System.in);
int x = cin.nextInt();
int y = cin.nextInt();
//方向
String go = "ULDR";
//地圖
int[][] map = new int[x][y];
//輸入
for(int i = ;i<x;i++)
for(int j = ;j<y;j++)
map[i][j] = cin.nextInt();
//初始位置及方向
x = cin.nextInt();
y = cin.nextInt();
char d = cin.next().charAt();
//将方向用下标表示,便于旋轉計算下一步的方向
int god = go.indexOf(d);
int num = cin.nextInt();
int temp = ;
//爬起來
for(int i = ;i<num;i++)
{
//改變地圖,旋轉方向
if(map[x][y] == )
{
map[x][y] = ;
temp = -;
}
else
{
map[x][y] = ;
temp = ;
}
//爬一步
god = (god-temp+)%;
switch(go.charAt(god))
{
case 'U':x--;break;
case 'L':y--;break;
case 'D':x++;break;
case 'R':y++;break;
}
}
sop1(x+" "+y);
}
public static void sop1(Object obj)
{
System.out.println(obj);
}
}