Skip to content

Shortest Path to Get Food

Leetcode 1730. Shortest Path to Get Food

Table of Contents

Leetcode 1730. Shortest Path to Get Food

Problem

You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.

You are given an m x n character matrix, grid, of these different types of cells:

  • '*' is your location. There is exactly one '*' cell.
  • '#' is a food cell. There may be multiple food cells.
  • 'O' is free space, and you can travel through these cells.
  • 'X' is an obstacle, and you cannot travel through these cells.

You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.

Return the length of the shortest path for you to reach any food cell. If there is no path for you to reach food, return -1.

Example 1:

Leetcode 1730. Shortest Path to Get Food
Leetcode 1730. Shortest Path to Get Food
Input: grid = [["X","X","X","X","X","X"],["X","*","O","O","O","X"],["X","O","O","#","O","X"],["X","X","X","X","X","X"]]
Output: 3
Explanation: It takes 3 steps to reach the food.

Example 2:

Leetcode 1730. Shortest Path to Get Food
Input: grid = [["X","X","X","X","X"],["X","*","X","O","X"],["X","O","X","#","X"],["X","X","X","X","X"]]
Output: -1
Explanation: It is not possible to reach the food.

Example 3:

Leetcode 1730. Shortest Path to Get Food
Input: grid = [["X","X","X","X","X","X","X","X"],["X","*","O","X","O","#","O","X"],["X","O","O","X","O","O","X","X"],["X","O","O","O","O","#","O","X"],["X","X","X","X","X","X","X","X"]]
Output: 6
Explanation: There can be multiple food cells. It only takes 6 steps to reach the bottom food.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • grid[row][col] is '*''X''O', or '#'.
  • The grid contains exactly one '*'.

Source: Leetcode 1730. Shortest Path to Get Food

Solution

This problem can be solved by a straight forward implementation of Breadth First Search algorithm. If we were asked to take all the foods with minimum length, the story would have been different though.

To apply BFS, we can take a queue and push the coordinates of source. Until we reach the coordinate of a single food, we will continue exploring neighbour nodes and push into the queue.

During this process, we will also keep track of distance passed so far. Once one of the food coordinates is found, we will return the destination so far plus one.

Below code is pretty simple to understand the above algorithm.

C++ Code
class Solution {
public:
    int getFood(vector<vector<char>>& grid) {
        
        queue<pair<int, int>> q;
        int R = grid.size();
        if(R == 0)
            return -1;
        
        int C = grid[0].size();
        if(C == 0)
            return -1;
        
        vector<vector<int>> visited(R, vector<int>(C, 0));
        for(int i = 0; i < R; i++){
            for(int j = 0; j < C; j++){
                if(grid[i][j] == '*'){
                    q.push({i, j});
                    visited[i][j] = 1;
                    break;
                }
            }
        }
        vector<vector<int>> dir{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
        int distance = 0;
        while(!q.empty()){
            int len = q.size();
            for(int l = 0; l < len; l++){
                pair<int, int> pr = q.front();
                q.pop();
                for(int i = 0; i < 4; i++){
                    int r = pr.first + dir[i][0];
                    int c = pr.second + dir[i][1];
                    if(0 <= r && r < R && 0 <= c && c < C){
                        if(grid[r][c] == '#')
                            return distance + 1;
                        if(grid[r][c] == 'O' && visited[r][c] == 0){
                            q.push({r, c});
                            visited[r][c] = 1;
                        }
                    }
                }
            }
            distance += 1;
        }
        return -1;   
    }
};
Conclusion

Hope you enjoyed this simple article about “Leetcode 1730. Shortest Path to Get Food.” Please leave a message for your valuable insights about this blog. Also, please feel free to browse other articles.

Happy coding! 🙂

44 thoughts on “Shortest Path to Get Food”

  1. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.

  2. Dear foolishhungry.com webmaster, You always provide clear explanations and step-by-step instructions.

  3. One Click Vids is a content innovator! It’s turbocharged my YouTube and TikTok content and made affiliate promotions a money-spinner. Get in on this—affordable and incredibly intuitive!

  4. One Click Vids is a creative powerhouse! It’s elevated my YouTube and TikTok game and made earning from affiliate offers a breeze. Dive into this gem—it’s affordable and ridiculously user-friendly!

  5. There are certainly lots of particulars like that to take into consideration. That may be a nice level to convey up. I offer the ideas above as normal inspiration but clearly there are questions just like the one you convey up where the most important factor might be working in sincere good faith. I don?t know if greatest practices have emerged round things like that, but I am sure that your job is clearly identified as a fair game. Both boys and girls really feel the impression of only a second’s pleasure, for the remainder of their lives.

  6. Of course like your website however you have to check the spelling on many of your posts. many of them are rife wih spelling issues and I find it very hard to inform the truth on the other hand I will likely come again again

  7. I liked it as much as you did. Even though the picture and writing are good, you’re looking forward to what comes next. If you defend this walk, it will be pretty much the same every time.

  8. To the foolishhungry.com owner, Thanks for the well-written and informative post!

  9. I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website

  10. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  11. I really like your writing style, wonderful info, appreciate it for putting up :D. “I hate mankind, for I think myself one of the best of them, and I know how bad I am.” by Joseph Baretti.

  12. I truly enjoy looking through on this website , it contains fantastic posts. “The longing to produce great inspirations didn’t produce anything but more longing.” by Sophie Kerr.

  13. Today, I went to the beachfront with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

  14. Simply want to say your article is as astonishing. The clarity on your submit is simply great and that i can assume you’re an expert on this subject. Fine with your permission allow me to seize your RSS feed to keep updated with coming near near post. Thanks a million and please continue the rewarding work.

  15. You actually make it appear so easy along with your presentation but I in finding this topic to be really one thing which I feel I might by no means understand. It seems too complicated and very huge for me. I’m having a look forward for your subsequent submit, I will try to get the grasp of it!

  16. It’s a pity you don’t have a donate button! I’d definitely donate to this outstanding blog! I suppose for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to new updates and will share this website with my Facebook group. Talk soon!

  17. Thank you for the good writeup. It in reality was once a entertainment account it. Look complicated to more delivered agreeable from you! By the way, how can we be in contact?

  18. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  19. Wonderful blog! I found it while searching on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Cheers

  20. Heya i am for the primary time here. I came across this board and I in finding It truly helpful & it helped me out a lot. I’m hoping to provide one thing again and aid others like you helped me.

  21. Appreciating the dedication you put into your blog and detailed information you offer. It’s nice to come across a blog every once in a while that isn’t the same unwanted rehashed material. Excellent read! I’ve saved your site and I’m including your RSS feeds to my Google account.

Leave a Reply

Your email address will not be published. Required fields are marked *