Table of Contents
Example
Input
Output
Home Backend Development C++ C++ program to find the number of jumps required by a robot to reach a specific cell in a grid

C++ program to find the number of jumps required by a robot to reach a specific cell in a grid

Sep 17, 2023 pm 07:17 PM
robot grid number of jumps

C++ program to find the number of jumps required by a robot to reach a specific cell in a grid

Suppose we have a grid of h x w. The grid is represented in a two-dimensional array called 'initGrid', where each cell in the grid is represented by a '#' or '.'. '#' means there is an obstacle in the grid, '.' means there is a path on that cell. Now, a robot is placed on a cell 'c' on the grid, which has row number x and column number y. The robot has to move from a cell 'd' with row number p and column number q to another cell. The cell coordinates c and d are both given as pairs of integers. Now the robot can move from one cell to another as follows:

  • If the cell the robot wants to move to is located vertically or horizontally adjacent to the current cell, the robot can walk directly from one cell to another.

  • The robot can jump to any cell in a 5x5 area centered on its current location.

  • The robot can only move to another cell in the grid that does not contain obstacles. The robot cannot leave the grid either.

We need to find out the number of hops it takes for the robot to reach the target.

So, if the input is h = 4, w = 4, c = {2, 1}, d = {4, 4}, initGrid = {"#...", ".##.", " ...#", "..#."}, then the output will be 1. The robot only needs one jump to reach its destination.

To solve this problem, we will follow the following steps:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

N:= 100

Define intger pairs s and t.

Define an array grid of size: N.

Define an array dst of size: N x N.

Define a struct node that contains integer values a, b, and e.

Define a function check(), this will take a, b,

   return a >= 0 AND a < h AND b >= 0 AND b < w

Define a function bfs(), this will take a, b,

   for initialize i := 0, when i < h, update (increase i by 1), do:

   for initialize j := 0, when j < w, update (increase j by 1), do:

      dst[i, j] := infinity

   dst[a, b] := 0

   Define one deque doubleq

   Insert a node containing values {a, b, and dst[a, b]} at the end of doubleq

   while (not doubleq is empty), do:

      nd := first element of doubleq

      if e value of nd > dst[a value of nd, b value of nd], then:

         Ignore the following part, skip to the next iteration

   for initialize diffx := -2, when diffx <= 2, update (increase diffx by 1), do:

   for initialize diffy := -2, when diffy <= 2, update (increase diffy by 1), do:

      tm := |diffx + |diffy||

      nx := a value of nd + diffx, ny = b value of nd + diffy

      if check(nx, ny) and grid[nx, ny] is same as &#39;.&#39;, then:

         w := (if tm > 1, then 1, otherwise 0)

         if dst[a value of nd, b value of nd] + w < dst[nx, ny], then:

            dst[nx, ny] := dst[a value of nd, b value of nd] + w

            if w is same as 0, then:

               insert node containing values ({nx, ny, dst[nx, ny]}) at the beginning of doubleq.

          Otherwise

insert node containing values ({nx, ny, dst[nx, ny]}) at the end of doubleq.

s := c

t := d

(decrease first value of s by 1)

(decrease second value of s by 1)

(decrease first value of t by 1)

(decrease second value of t by 1)

for initialize i := 0, when i < h, update (increase i by 1), do:

grid[i] := initGrid[i]

bfs(first value of s, second value of s)

print(if dst[first value of t, second value of t] is same as infinity, then -1, otherwise dst[first value of t, second value of t])

Copy after login

Example

Let us see the implementation below to get a better understanding −

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

#include <bits/stdc++.h>

using namespace std;

const int INF = 1e9;

#define N 100

int h, w;

pair<int, int> s, t;

string grid[N];

int dst[N][N];

struct node {

   int a, b, e;

};

bool check(int a, int b) {

   return a >= 0 && a < h && b >= 0 && b < w;

}

void bfs(int a, int b) {

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

      for (int j = 0; j < w; j++)

         dst[i][j] = INF;

   }

   dst[a][b] = 0;

   deque<node> doubleq;

   doubleq.push_back({a, b, dst[a][b]});

 

   while (!doubleq.empty()) {

      node nd = doubleq.front();

      doubleq.pop_front();

      if (nd.e > dst[nd.a][nd.b])

         continue;

      for (int diffx = -2; diffx <= 2; diffx++) {

         for (int diffy = -2; diffy <= 2; diffy++) {

            int tm = abs(diffx) + abs(diffy);

            int nx = nd.a + diffx, ny = nd.b + diffy;

            if (check(nx, ny) && grid[nx][ny] == &#39;.&#39;) {

               int w = (tm > 1) ? 1 : 0;

               if (dst[nd.a][nd.b] + w < dst[nx][ny]) {

                  dst[nx][ny] = dst[nd.a][nd.b] + w;

                  if (w == 0)

                     doubleq.push_front({nx, ny, dst[nx][ny]});

                  else

                     doubleq.push_back({nx, ny, dst[nx][ny]});

               }

            }

         }

      }

   }

}

void solve(pair<int,int> c, pair<int, int> d, string initGrid[]){

   s = c;

   t = d;

   s.first--, s.second--, t.first--, t.second--;

   for(int i = 0; i < h; i++)

      grid[i] = initGrid[i];

   bfs(s.first, s.second);

   cout << (dst[t.first][t.second] == INF ? -1 :

      dst[t.first][t.second]) << &#39;\n&#39;;

}

int main() {

   h = 4, w = 4;

   pair<int,int> c = {2, 1}, d = {4, 4};

   string initGrid[] = {"#...", ".##.", "...#", "..#."};

   solve(c, d, initGrid);

   return 0;

}

Copy after login

Input

1

4, 4, {2, 1}, {4, 4}, {"#...", ".##.", "...#", "..#."}

Copy after login

Output

1

1

Copy after login

The above is the detailed content of C++ program to find the number of jumps required by a robot to reach a specific cell in a grid. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Multi-grid redundant bounding box annotation for accurate object detection Multi-grid redundant bounding box annotation for accurate object detection Jun 01, 2024 pm 09:46 PM

1. Introduction Currently, the leading object detectors are two-stage or single-stage networks based on the repurposed backbone classifier network of deep CNN. YOLOv3 is one such well-known state-of-the-art single-stage detector that receives an input image and divides it into an equal-sized grid matrix. Grid cells with target centers are responsible for detecting specific targets. What I’m sharing today is a new mathematical method that allocates multiple grids to each target to achieve accurate tight-fit bounding box prediction. The researchers also proposed an effective offline copy-paste data enhancement for target detection. The newly proposed method significantly outperforms some current state-of-the-art object detectors and promises better performance. 2. The background target detection network is designed to use

The second generation Ameca is here! He can communicate with the audience fluently, his facial expressions are more realistic, and he can speak dozens of languages. The second generation Ameca is here! He can communicate with the audience fluently, his facial expressions are more realistic, and he can speak dozens of languages. Mar 04, 2024 am 09:10 AM

The humanoid robot Ameca has been upgraded to the second generation! Recently, at the World Mobile Communications Conference MWC2024, the world's most advanced robot Ameca appeared again. Around the venue, Ameca attracted a large number of spectators. With the blessing of GPT-4, Ameca can respond to various problems in real time. "Let's have a dance." When asked if she had emotions, Ameca responded with a series of facial expressions that looked very lifelike. Just a few days ago, EngineeredArts, the British robotics company behind Ameca, just demonstrated the team’s latest development results. In the video, the robot Ameca has visual capabilities and can see and describe the entire room and specific objects. The most amazing thing is that she can also

How can AI make robots more autonomous and adaptable? How can AI make robots more autonomous and adaptable? Jun 03, 2024 pm 07:18 PM

In the field of industrial automation technology, there are two recent hot spots that are difficult to ignore: artificial intelligence (AI) and Nvidia. Don’t change the meaning of the original content, fine-tune the content, rewrite the content, don’t continue: “Not only that, the two are closely related, because Nvidia is expanding beyond just its original graphics processing units (GPUs). The technology extends to the field of digital twins and is closely connected to emerging AI technologies. "Recently, NVIDIA has reached cooperation with many industrial companies, including leading industrial automation companies such as Aveva, Rockwell Automation, Siemens and Schneider Electric, as well as Teradyne Robotics and its MiR and Universal Robots companies. Recently,Nvidiahascoll

The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training The first robot to autonomously complete human tasks appears, with five fingers that are flexible and fast, and large models support virtual space training Mar 11, 2024 pm 12:10 PM

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects

After 2 months, the humanoid robot Walker S can fold clothes After 2 months, the humanoid robot Walker S can fold clothes Apr 03, 2024 am 08:01 AM

Editor of Machine Power Report: Wu Xin The domestic version of the humanoid robot + large model team completed the operation task of complex flexible materials such as folding clothes for the first time. With the unveiling of Figure01, which integrates OpenAI's multi-modal large model, the related progress of domestic peers has been attracting attention. Just yesterday, UBTECH, China's "number one humanoid robot stock", released the first demo of the humanoid robot WalkerS that is deeply integrated with Baidu Wenxin's large model, showing some interesting new features. Now, WalkerS, blessed by Baidu Wenxin’s large model capabilities, looks like this. Like Figure01, WalkerS does not move around, but stands behind a desk to complete a series of tasks. It can follow human commands and fold clothes

Ten humanoid robots shaping the future Ten humanoid robots shaping the future Mar 22, 2024 pm 08:51 PM

The following 10 humanoid robots are shaping our future: 1. ASIMO: Developed by Honda, ASIMO is one of the most well-known humanoid robots. Standing 4 feet tall and weighing 119 pounds, ASIMO is equipped with advanced sensors and artificial intelligence capabilities that allow it to navigate complex environments and interact with humans. ASIMO's versatility makes it suitable for a variety of tasks, from assisting people with disabilities to delivering presentations at events. 2. Pepper: Created by Softbank Robotics, Pepper aims to be a social companion for humans. With its expressive face and ability to recognize emotions, Pepper can participate in conversations, help in retail settings, and even provide educational support. Pepper's

The humanoid robot can do magic, let the Spring Festival Gala program team find out more The humanoid robot can do magic, let the Spring Festival Gala program team find out more Feb 04, 2024 am 09:03 AM

In the blink of an eye, robots have learned to do magic? It was seen that it first picked up the water spoon on the table and proved to the audience that there was nothing in it... Then it put the egg-like object in its hand, then put the water spoon back on the table and started to "cast a spell"... …Just when it picked up the water spoon again, a miracle happened. The egg that was originally put in disappeared, and the thing that jumped out turned into a basketball... Let’s look at the continuous actions again: △ This animation shows a set of actions at 2x speed, and it flows smoothly. Only by watching the video repeatedly at 0.5x speed can it be understood. Finally, I discovered the clues: if my hand speed were faster, I might be able to hide it from the enemy. Some netizens lamented that the robot’s magic skills were even higher than their own: Mag was the one who performed this magic for us.

Cloud Whale Xiaoyao 001 sweeping and mopping robot has a 'brain'! | Experience Cloud Whale Xiaoyao 001 sweeping and mopping robot has a 'brain'! | Experience Apr 26, 2024 pm 04:22 PM

Sweeping and mopping robots are one of the most popular smart home appliances among consumers in recent years. The convenience of operation it brings, or even the need for no operation, allows lazy people to free their hands, allowing consumers to "liberate" from daily housework and spend more time on the things they like. Improved quality of life in disguised form. Riding on this craze, almost all home appliance brands on the market are making their own sweeping and mopping robots, making the entire sweeping and mopping robot market very lively. However, the rapid expansion of the market will inevitably bring about a hidden danger: many manufacturers will use the tactics of sea of ​​machines to quickly occupy more market share, resulting in many new products without any upgrade points. It is also said that they are "matryoshka" models. Not an exaggeration. However, not all sweeping and mopping robots are

See all articles