01/10/2018, 00:57

Ai có cách hay giải bài như này không ạ?

You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones – everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. [‘n’, ‘s’, ‘w’, ‘e’]). You know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don’t want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.

Note: you will always receive a valid array containing a random assortment of direction letters (‘n’, ‘s’, ‘e’, or ‘w’ only). It will never give you an empty array (that’s not a walk, that’s standing still!).

Blad viết 03:08 ngày 01/10/2018

Bài này có thấy gì phức tạp đâu, chỉ di chuyển theo 4 hướng, mỗi bước chỉ đi theo 1 trong 4 hướng (ứng với 1 phút).
Vị trí ban đầu tọa độ (x0=0,y0=0), các hướng định nghĩa như sau:
n (0,1) - x ko đổi, y tăng 1
s (0,-1) …
w (-1,0) …
e (1,0) …

If length của mảng < 10 return false; (mỗi lần đi 1 phút thì ít cũng phải đi 10 bước chớ)
Duyệt mảng, cộng dồn giá trị các bước vào để ra vị trí hiện tại (x,y)
If (abs(x)+abs(y) > 5) return false; (vì đi xa quá 5 đơn vị thì ko thể quay về kịp dc)
If (x==0 && y==0) && count == 10 return true;
return false;

Bài liên quan
0