Walls and Gates

Sdílet
Vložit
  • čas přidán 5. 07. 2024
  • For business inquiries email partnerships@k2.codes Discord: bit.ly/K2-discord
  • Věda a technologie

Komentáře • 98

  • @KevinNaughtonJr
    @KevinNaughtonJr  Před 5 lety +9

    If you need help with anything feel free to shoot me a message on Instagram or scope my Patreon to join the Discord server (links are in the description)!

    • @algorithmimplementer415
      @algorithmimplementer415 Před 4 lety

      Kevin Naughton Jr. Would it be possible to replace this video with an alternate one with efficient solution which is BFS? Please consider the time complexity of this dfs solution. It’s terribly slow.
      After all, interviewers expect the candidates to provide efficient solution at the interview. When shortest path is mentioned in this, I wonder why you skipped any shortest path finding algorithm to solve it.
      Thank you.

    • @darod6098
      @darod6098 Před 4 lety

      @@algorithmimplementer415 Why do you think that time complexity of this solution is worse than a bfs solution?

    • @mhelvens
      @mhelvens Před 4 lety +1

      @@darod6098 For BFS, if you seed the queue with all gate cells, you then only have to visit every cell at most once, for a worst-case runtime of O(R*C), for row-count R and col-count C.
      With a sufficiently unlucky testcase it seems like the DFS algorithm presented in the video could flood-fill the entire space many times. At least once per gate, but probably even multiple times from a single gate, so long as every time it overwrites the cells with slightly lower values.

    • @veenaprabhudesai
      @veenaprabhudesai Před 4 lety

      Hi Kevin, Thank you for your video. Can you please show a BFS solution of this problem?

    • @thinkindependently138
      @thinkindependently138 Před 3 lety

      Kevin, why you did not detect circle and avoid around situation?

  • @georgesmith9178
    @georgesmith9178 Před 3 lety +21

    Thank you, Kevin. Thumbs up as usual.
    Small addition to enhance understanding:
    rooms[i][j] < count - the MOST IMPORTANT check also because it covers walls as well, i.e. cells with value -1. Those cells will NOT be updated because their value is ALWAYS < count

    • @adrianfiedler3520
      @adrianfiedler3520 Před 3 lety +1

      Ah right, I wondered why no check if it is a wall with -1. But of course, it is always < count.

    • @AstroTibs
      @AstroTibs Před 2 lety

      @@adrianfiedler3520 I'm still confused about a detail. If we don't *return;* when we encounter a -1, won't it count it like an empty cell for the purposes of iteration? Wouldn't an empty cell record the distance to the closest gate, _including_ through a wall?
      Or, put another way, if you had a room fully closed off by walls with no gate within, won't that room still fill with distances to the nearest (outside) gate?
      I think including the condition *rooms[col][row] == -1* for the first *return;* statement would cover this.

    • @dss963
      @dss963 Před rokem

      @@AstroTibs naah...that won't be filled...because for any gates outside this region you said, as we start the recursion from the gate we will always stop and return the recursion from the wall as its value which is -1, is always less than any number >=0.

  • @HoySiComi
    @HoySiComi Před 4 lety +38

    Sheez I watch all your videos except this..., this was my interview question :(

  • @bewareofnikhil
    @bewareofnikhil Před 2 lety +8

    I think BFS is already optimized for this question. With DFS, you will have to check if the distances calcualted is better than any previous distance. This would not be the case with BFS.

  • @VC-kj9yx
    @VC-kj9yx Před 4 lety

    Kevin is the best. He explains the logic and writes the code too. I really appreciate your hard work Kevin. Please keep making these videos. O feel if I would have seen your videos before my Microsoft interview then probably I might have got a job offer

  • @algorithmimplementer415
    @algorithmimplementer415 Před 4 lety +6

    I must thank you as when I watch your videos I feel confident about coding before the interview. :) Please keep on uploading more videos. :)

  • @christopherlee3311
    @christopherlee3311 Před 3 lety

    you're the man. this solution is simpler than the results I've seen in the LC discussion board (for JS).

  • @aarushi6601
    @aarushi6601 Před 3 lety

    Thanks for making the dfs codes so easy to grasp like all the other videos.

  • @Niro_Hero
    @Niro_Hero Před 2 lety +1

    Hi Kevin,
    First of all your'e super awesome. Your'e videos really helped allot to get FAANG offers :)
    This specific video needs to be updates as you will get a TLE using this algorithm.
    This basically needs to be a BFS which runs on queue which runs on queue once all cords with 0 have been set on the queue.

  • @saurabhdeshmukh6828
    @saurabhdeshmukh6828 Před 4 lety +2

    Thanks a ton! Keep up the great work!
    Some more similar dfs problems on leetcode:
    Number of Islands
    Maximum Area of Island
    Battleships on a board

  • @NotesNaka
    @NotesNaka Před 4 lety +1

    Thanks for the awesome video 😊

  • @DineshSelvaraj1803
    @DineshSelvaraj1803 Před 4 lety

    I was reading this in leet code and had trouble understanding. But this video really helped. Thanks Kevin.

  • @goodwish1543
    @goodwish1543 Před 5 lety +3

    It's short and concise. Thanks for teaching.

  • @swagatpatra2139
    @swagatpatra2139 Před 3 lety

    Just one question, can we use DP here? We can store the min distance from 0 and then increment by one. Pls tell.

  • @sophia0282
    @sophia0282 Před 2 lety

    Thank you for the great explanation!

  • @Od253
    @Od253 Před 4 lety

    Such a great problem. Thanks for the video.

  • @dineshbhonsle6524
    @dineshbhonsle6524 Před 3 lety

    Great explanation. Thanks

  • @Nobody2310
    @Nobody2310 Před 5 lety +11

    Kevin, great explanation! I have trouble understanding weather to use dfs or bfs in these kind of problems. Whenever I hear shortest distance I tend to use BFS but in this problem using DFS we got the same result, how to figure out if a problem is well suited for BFS or DFS? Is it like BFS is more suited for shortest distance to one destination and DFS for all pair shortest distance?

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 5 lety +9

      Hey Nitish, yeah it can be tricky trying to pick bfs or dfs. Generally speaking when you're trying to find the shortest path from point A to point B you should opt to use BFS (assuming all edge weights are 1) , it'll help ensure that you don't go down any crazy rabbit hole like you can in DFS. So, in retrospect, although the runtimes don't differ in the worst case, it probably would've been best to use BFS in this problem

    • @mhelvens
      @mhelvens Před 4 lety +6

      @@KevinNaughtonJr Isn't the worst-case runtime complexity better for BFS though? You seed the queue with all gate cells, and then you only have to visit every cell at most once, for a worst-case runtime of O(R*C), for row-count R and col-count C.
      With an unlucky testcase it seems like your DFS algorithm could flood-fill the entire space many times. At least once per gate, but probably even multiple times from a single gate, so long as every time you overwrite the cells with slightly lower values.

    • @vtvtify
      @vtvtify Před 3 lety +1

      Multi BFS works here aswell.

    • @mostafaelmenbawy5473
      @mostafaelmenbawy5473 Před 2 lety

      @@mhelvens
      That's what's called multi-source BFS

  • @MorisonMs
    @MorisonMs Před 5 lety +1

    I enjoy your videos brother.
    Let N,M be the number of nodes, edges in a general graph.
    This problem can be solved in M+Nlog(N) time in a fashion similar to Dijkstra. Your algorithm runs in N(N+M) time.
    In our case M=O(N) --> Nlog(N) vs N^2

  • @siddhantmisra5664
    @siddhantmisra5664 Před 5 lety +3

    They asked the spiral matrix question recently. I was stumped but still did it more or less.

  • @kingdavey87
    @kingdavey87 Před 4 lety

    What's the difference between adding to count parameter in dfs function call and incrementing count in the processing prior to that?
    And why doesnt the solution return the board? Is this stated in the problem?

  • @IOSAppCrazy
    @IOSAppCrazy Před 3 lety +1

    This solution rechecks nodes multiple times. If you BFS every gate simultaneously, you only have to update a node once.

  • @taimurkhaliq4477
    @taimurkhaliq4477 Před 2 lety

    nice video. Really well explained.

  • @bohao9046
    @bohao9046 Před 3 lety +5

    This solution seems no longer working, it's going to time out. Need to add some condition when doing dfs like this:
    if(r < rooms.length - 1 && count+1 < rooms[r+1][c]){
    dfs(r+1, c, count+1, rooms);
    }
    if(r > 0 && count+1 < rooms[r-1][c]){
    dfs(r-1, c, count+1, rooms);
    }
    if(c < rooms[r].length-1 && count+1 < rooms[r][c+1]){
    dfs(r, c+1, count+1, rooms);
    }
    if(c > 0 && count+1 < rooms[r][c-1]){
    dfs(r, c-1, count+1, rooms);
    }

    • @dengpanyuan1363
      @dengpanyuan1363 Před 3 lety +1

      Great fix!

    • @jiecheng.x1306
      @jiecheng.x1306 Před rokem

      Thanks! It works. But I am a little confused. These different if conditions look like the same meaning as the if condition at the beginning (which then return; )

  • @anupbid
    @anupbid Před 7 měsíci

    Where do you get these crazy into musics from from?

  • @nikhilmylarapu7349
    @nikhilmylarapu7349 Před 4 lety

    You are awesome man!

  • @arungiri8560
    @arungiri8560 Před 4 lety

    You are great man!!

  • @TeluguUSDiaries
    @TeluguUSDiaries Před 4 lety +16

    how come it's not considering the -1(walls). Meaning how come we didn't check anything related to -1 here? Can someone please explain?

    • @0anant0
      @0anant0 Před 4 lety +21

      if (board[row][col] < distance) return (this check is combined with out of bounds check); We start with distance = 0, and wall = -1, so walls are implicitly ignored!

    • @Jimmy-ng3ci
      @Jimmy-ng3ci Před 4 lety +4

      @@0anant0 Thanks man that's smart not sure if he mentioned it in the video

    • @Sanjith9525
      @Sanjith9525 Před 4 lety +2

      room[i][j]< count is one of the conditions where the dfs returns. count will always be greater than -1.

    • @waterislife9
      @waterislife9 Před 4 lety +1

      The problem is designed to represent 'Gates' as 0 and 'Walls' as 1, so while matrix[i][j] = count overwrite the original starting dfs location, count will always be 0, thus no net change; if Gates were 'G' and Walls were 'W', then we can introduce additional if checks to respond appropriately.

    • @tejassameera8962
      @tejassameera8962 Před 4 lety

      Yeah he didn’t mention it but the out of bounds check covered it

  • @ericj1380
    @ericj1380 Před 4 lety

    Could you explain why the time complexity is O(m*n) for this one? I understand that we are traversing through the entire grid which is m*n but do we not consider the recursive calls of dfs?

    • @gsb22
      @gsb22 Před 3 lety

      Worst case scenario, we have gate in bottom right cell and for each cell we run dfs which results in ( m*n) times for (m*n) cells, which is m2n2

  • @alexb6568
    @alexb6568 Před 3 lety +1

    One thing: It is just a coincidence this works as all the test case cells can reach a gate. There is no "inserting INF" in your solution, unlike what the Leetcode stipulates. That said, if the test cases do not cover that possibility, that is not your problem. Good video, obviously.

    • @alexb6568
      @alexb6568 Před 3 lety +1

      By the way, anyone know how to turn off the annoying Algoexpert girl?

    • @adrianfiedler3520
      @adrianfiedler3520 Před 3 lety

      I think you don't have to insert INF, as they are already initialized with INF. So I you can't reach it, it will still be INF and should work.

  • @renetchi
    @renetchi Před 3 lety

    This is really similar to the island questions

  • @dhunvirai3810
    @dhunvirai3810 Před 4 lety +2

    How would bfs code change as compared to dfs?

  • @nimachitsazan6989
    @nimachitsazan6989 Před 3 lety

    Hi - Thanks for the video. I'd appriciate if you could answer this question:

  • @scy1990s
    @scy1990s Před 2 lety

    It's such a clean and easy to understand solution, but now it gives TLE (June 7th 2022).

  • @brothermalcolm
    @brothermalcolm Před 2 lety

    Idea: undirected graph traversal
    Create adjacency list
    Perform DFS at every node
    Until wall is reached
    Save shortest path

  • @mevam123
    @mevam123 Před 3 lety +3

    This code gives TLE now

  • @emran1095
    @emran1095 Před 3 lety

    why not use r and c when its matrix ? :) it will help us to understand . Thanks for your videos Kevin .

  • @rahoolification
    @rahoolification Před 4 lety

    Fantastic explanation!

  • @aravindhsaairavichandran8404

    Dude thanks for teaching .. LC solution was complicated for me

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 4 lety

      Aravindh Saai Ravichandran anytime! Check out the interviewing service I made if you need help with understanding problems like this thedailybyte.dev/?ref=kevin I’d join a premium plan if you can!

  • @sharkk2979
    @sharkk2979 Před 3 lety +3

    Hey kevin, if u readin it, i very much liked the last condition in if in dfs
    I got high on on how it takes care of walls.

    • @chiraggarg96
      @chiraggarg96 Před 3 lety

      room[i][j] < count will handle the condition for walls, as wall is equal to -1 that will always less than count;

  • @cbjueueiwyru7472
    @cbjueueiwyru7472 Před 3 lety

    Will this solution overwrite other gates?

  • @Ty1er
    @Ty1er Před 11 měsíci

    Holes and caves

  • @anoopjoy501
    @anoopjoy501 Před 3 lety

    What is the time complexity of this solution?

  • @aravindreddy3230
    @aravindreddy3230 Před 2 lety

    This solution is exceeding timelimit! I wonder how i got submitted for you:)

  • @vanditshah7625
    @vanditshah7625 Před 3 lety

    This has now become a leetcode premium question.😑

  • @ramatripathi8315
    @ramatripathi8315 Před 2 lety

    really nice explanation ! one suggestion is if you could use animations to explain the solution , that could really help us to understand in much better way .

  • @Melroph
    @Melroph Před 4 lety

    I can't understand the recursive part at 6:09 can someone pls explain?

  • @s1337m
    @s1337m Před 5 lety +1

    What's the runtime complexity? Seems we can traverse the grid N times where N is a gate

    • @hrishikeshkulkarni2856
      @hrishikeshkulkarni2856 Před 5 lety

      We're doing standard DFS for matrix representation of n*n. Thus seems time complexity is O(n*n)

    • @goodwish1543
      @goodwish1543 Před 5 lety +3

      O(number of 0s * number of cells)

    • @foo.1396
      @foo.1396 Před 3 lety

      @@goodwish1543 (number of rows * number of cols) + (number of 0s * number of rows * number of cols)

  • @shankarsuman8801
    @shankarsuman8801 Před 3 lety

    I have been leetcoding for past 1 year , Is 1 more year of leetcoding enough to crack FANG internship?

    • @KevinNaughtonJr
      @KevinNaughtonJr  Před 3 lety

      hard to say because it depends on comfortable you are with these questions and topics. If you need help preparing for these interviews I'd suggest signing up for the interviewing service I created thedailybyte.dev/?ref=kevin I'd join the annual plan if you can!

  • @GChief117
    @GChief117 Před 2 lety

    Update Time Limit Exceeded for this.

  • @Makwayne
    @Makwayne Před 2 lety +2

    TLE (23rd Nov 2021)

  • @Ananya807
    @Ananya807 Před 3 měsíci

    1:57 is where the solution starts

  • @raghunadh_g
    @raghunadh_g Před 4 lety

    Ur bgm pls😂😅

  • @sharmilabaskaran7373
    @sharmilabaskaran7373 Před 4 lety

    I am not sure how this would ignore Walls while traversing.

    • @rocyjei
      @rocyjei Před 4 lety

      It doesn't, actually it just evaluate this cells as counts with big values, so the first condition rooms[i][j] < count skips this cells

  • @prathamkesarkar
    @prathamkesarkar Před 3 lety +2

    Trump Voter's favorite question

  • @rishabkumar4940
    @rishabkumar4940 Před 2 lety

    We can solve it using multisource BFS in a very optimal way. Just add all the gates into the queue and keep on traversing level by level keeping the track of the visited cells. It can be solved in O(n*m) time complexity.

  • @scy1990s
    @scy1990s Před 2 lety

    It's such a clean and easy to understand solution, but now it gives TLE (June 7th 2022).