题目描述
你被困在一个多层停车场。您的任务是仅使用楼梯离开停车场。出口总是在一楼的右下角。 创建一个采用矩阵的函数,其中:
0
表示免费停车位。1
表示楼梯。2
表示您的起始位置,可以在停车场的任何一层。- 出口总是在一楼的右下角。
- 您必须使用楼梯
1
才能下一层。 - 除了一楼,每一层只有一个楼梯,一楼没有任何楼梯。 请你设计并返回一个最快离开停车场的字符串。
输入输出格式
输入格式
第一行 N
表示循环的次数。
第二行有 test_data
表示 测试数据的字符串,这些字符串中间都用空格隔开。
输出格式
返回离开停车场的字符串。
输入输出样例1
输入
2
1 0 0 0 2
0 0 0 0 0
输出
L4 D1 R4
输入输出样例2
输入
3
2 0 0 1 0
0 0 0 1 0
0 0 0 0 0
输出
R3 D2 R1
解释
表示向右走三下,向下走两下,再向右走一下。
说明提示
arr = [
[1, 0, 0, 0, 2],
[0, 0, 0, 0, 0]
]
# 从2开始,向左移动4次=“L4”
# 从楼梯下 1 步 = “D1”
# 向右移动 4 次从右下角退出 = "R4"
【Java代码及解题思路】
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
// 房间数组
int[][] a = new int[n][5];
// 当前位置:0 纵坐标;1 横坐标;
int[] pos = new int[2];
// n层只有n-1个楼梯
int len = n-1;
int[] stairs = new int[len];
for(int i = 0;i<n;i++){
for (int j = 0;j < 5;j++){
a[i][j] = scanner.nextInt();
if(a[i][j]==2){
// 更新当前位置
pos[0] = i;
pos[1] = j;
}else if(a[i][j]==1){
// 记录楼梯位置
stairs[i] = j;
}
}
}
// 移动操作:0 方向;1 步数;(n层最多有2n个移动操作:平移+下楼)
String[][] move= new String[2*n][2];
// 索引
int index = 0;
// 循环
while(true){
// 如果当前位置在有出口的一层(最下层)
if(pos[0]==n-1){
// 如果当前位置在出口,则直接break;
if(pos[1]==4){
break;
}else { // 如果不在出口,一定向右移动
move[index][0] = "R"; // 方向
move[index][1] = String.valueOf(4-pos[1]); // 步数
//索引++
index++;
// 更新当前位置,只更新横坐标
pos[1] = 4;
break;
}
}
//如果在楼梯口处
if(pos[1]==stairs[pos[0]]){
// 向下移动几层
int downCount = 0;
int k = 0;
// 如果下面也是楼梯口则满足循环
while (pos[0]+k<len && stairs[pos[0]+k]==stairs[pos[0]]){
downCount++;
k++;
}
// 向下移动
move[index][0] = "D";
move[index][1] = String.valueOf(downCount);
index++;
// 更新当前位置
pos[0] = pos[0] + downCount;
}else { // 如果不在楼梯口
// 如果在楼梯口右边,则向左移动
if(pos[1]>stairs[pos[0]]){
move[index][0] = "L";
move[index][1] = String.valueOf(pos[1]-stairs[pos[0]]);
index++;
// 更新当前位置
pos[1] = stairs[pos[0]];
}else { // 如果在楼梯口左边,则向右移动
move[index][0] = "R";
move[index][1] = String.valueOf(stairs[pos[0]]-pos[1]);
index++;
// 更新当前位置
pos[1] = stairs[pos[0]];
}
}
}
// 输出move
for(int i = 0;i<index;i++){
if(move[i][0]!=null&&move[i][1]!=null){
System.out.print(move[i][0]+""+move[i][1]+" ");
}
}
}
}