我们从一块字母板上的位置 (0, 0)
出发,该坐标对应的字符为 board[0][0]
。
在本题里,字母板为board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
.
我们可以按下面的指令规则行动:
- 如果方格存在,
'U'
意味着将我们的位置上移一行; - 如果方格存在,
'D'
意味着将我们的位置下移一行; - 如果方格存在,
'L'
意味着将我们的位置左移一列; - 如果方格存在,
'R'
意味着将我们的位置右移一列; '!'
会把在我们当前位置(r, c)
的字符board[r][c]
添加到答案中。
返回指令序列,用最小的行动次数让答案和目标 target
相同。你可以返回任何达成目标的路径。
示例 1:
输入:target = "leet" 输出:"DDR!UURRR!!DDD!"
示例 2:
输入:target = "code" 输出:"RR!DDRR!UUL!R!"
提示:
1 <= target.length <= 100
target
仅含有小写英文字母。
C++
class Solution {
public:
string alphabetBoardPath(string target)
{
map<char,pair<int,int>> tmp;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
char c=(i*5+j)+'a';
tmp[c]=make_pair(i,j);
}
}
tmp['z']=make_pair(5,0);
pair<int,int> start=make_pair(0,0);
string res;
int n=target.length();
for(int i=0;i<n;i++)
{
char c=target[i];
if(start==tmp[c])
{
res+='!';
}
else
{
if('z'==c || tmp['z']==start)
{
if('z'==c)
{
int h=tmp[c].second-start.second;
int v=tmp[c].first-start.first;
if(h<0)
{
for(int s=0;s<abs(h);s++)
{
res+='L';
}
}
if(v>0)
{
for(int s=0;s<v;s++)
{
res+='D';
}
}
res+='!';
start=tmp[c];
}
else
{
int v=tmp[c].first-start.first;
int h=tmp[c].second-start.second;
if(v<0)
{
for(int s=0;s<abs(v);s++)
{
res+='U';
}
}
if(h>0)
{
for(int s=0;s<h;s++)
{
res+='R';
}
}
res+='!';
start=tmp[c];
}
}
else
{
int v=tmp[c].first-start.first;
int h=tmp[c].second-start.second;
if(v<0)
{
for(int s=0;s<abs(v);s++)
{
res+='U';
}
}
else
{
for(int s=0;s<v;s++)
{
res+='D';
}
}
if(h<0)
{
for(int s=0;s<abs(h);s++)
{
res+='L';
}
}
else
{
for(int s=0;s<h;s++)
{
res+='R';
}
}
res+='!';
start=tmp[c];
}
}
}
return res;
}
};