Regions Cut By Slashes - Leetcode 959 - Python

Поділитися
Вставка
  • Опубліковано 15 гру 2024

КОМЕНТАРІ • 127

  • @StellasAdi18
    @StellasAdi18 4 місяці тому +60

    This is crazy. This problem should be hard. Is it just me who solved island type problems 10+ times but could not associate this is similar to that? I was looking at if there are patterns to count regions row wise.

  • @zoozoo24
    @zoozoo24 4 місяці тому +131

    The fuck

  • @gmh14
    @gmh14 4 місяці тому +13

    I wish I came up with this solution. I would have jumped out of my window because I could fly

  • @business_central
    @business_central 4 місяці тому +16

    take the grid and make it 3 times bigger, no way a normal person would think of exactly that in an interview.
    Thanks for the run Neetcode! Btw no streams for a quite a while, hope to see them back soon

    • @krishnabisht-o4e
      @krishnabisht-o4e 4 місяці тому

      Future ain't waiting for normal people

    • @deepakjain4481
      @deepakjain4481 4 місяці тому

      @@krishnabisht-o4e it is just need to work hard though

  • @BrandonGarciaCode01
    @BrandonGarciaCode01 4 місяці тому +27

    5:32 At this point I even do not undertand the problem.

    • @dashdoom8452
      @dashdoom8452 4 місяці тому

      I don't even understand how we are supposed to parse the input

  • @АнасБенМустафа
    @АнасБенМустафа 4 місяці тому +6

    Learned a lot from the problem, but it's definitely not a medium :) Thanks for the explanation!

  • @neelpatel4330
    @neelpatel4330 4 місяці тому +1

    I managed to solve that question with 2n X 2n grid instead of 3x X 3x.
    I replace / with 1 and \ with -1 and call dfs for all direction as well as for diagonal for specific condition and it works!
    class Solution:
    def regionsBySlashes(self, grid: List[str]) -> int:
    n = len(grid)
    main_grid = [[0 for _ in range(n*2)] for _ in range(n*2)]
    m = n*2
    for i in range(n):
    for j in range(n):
    if grid[i][j] == '/':
    main_grid[i*2 + 1][j*2] = 1
    main_grid[i*2][j*2 + 1] = 1
    elif grid[i][j] == '\\':
    main_grid[i*2][j*2] = -1
    main_grid[i*2 + 1][j*2 + 1] = -1
    visited = set()

    def dfs(i, j):
    if i == -1 or j == -1 or i == m or j == m or main_grid[i][j] or (i, j) in visited:
    return

    visited.add((i, j))
    dfs(i, j+1)
    dfs(i+1, j)
    dfs(i, j-1)
    dfs(i-1, j)
    if i != 0 and j != m-1 and main_grid[i-1][j] != -1 and main_grid[i][j+1] != -1:
    dfs(i-1, j+1)

    if i != m-1 and j != 0 and main_grid[i][j-1] != -1 and main_grid[i+1][j] != -1:
    dfs(i+1, j-1)

    if i != m-1 and j != m-1 and main_grid[i][j+1] != 1 and main_grid[i+1][j] != 1:
    dfs(i+1, j+1)

    if i != 0 and j != 0 and main_grid[i][j-1] != 1 and main_grid[i-1][j] != 1:
    dfs(i-1, j-1)


    ans = 0
    for i in range(m):
    for j in range(m):
    if main_grid[i][j] == 0 and (i, j) not in visited:
    dfs(i, j)
    ans += 1

    return ans

  • @ashishbhambure7227
    @ashishbhambure7227 4 місяці тому +26

    The space complexity will be 9*n^2 bcoz each cell needs 9 more cells for scaling .

    • @hashedbrowns
      @hashedbrowns 4 місяці тому +5

      You don't count constants when calculating space complexity so it will be n^2

    • @samettekin2356
      @samettekin2356 4 місяці тому

      You need to check to definition of big o notation. You don't add the constants to the notation as they are not defining factors on runtime complexity or space complexity as the input size reaches infinity.

    • @julianelmasry9556
      @julianelmasry9556 4 місяці тому

      can you use that same logic for the runtime complexity. 9*n^2 rather than 3*n^2

  • @dasav6724
    @dasav6724 4 місяці тому +15

    5:31 Jumpscare warning

  • @fieworjohn5697
    @fieworjohn5697 4 місяці тому +1

    Hey @neetcodeIO .You can use Ctrl+D to "select next occurrence". It will help you correct stuff faster/more easily. I've noticed you edit separately (like you did in 15:36 with the grid2) in several vids and just thought to point it out.

  • @anandsrikumar007
    @anandsrikumar007 4 місяці тому +4

    This is flood fill algorithm. I realized it the moment I read the problem statement. I watched this video, the moment i heard that i can divide the char into a grid of 3x3, I understood the problem, solved it myself.

  • @確實-r4x
    @確實-r4x 4 місяці тому +1

    Crazy and actually a great problem. thanks for video!!

  • @jamestwosheep
    @jamestwosheep 4 місяці тому +3

    I managed to solve this one by dividing each cell into 4 triangular quadrants along the diagonals - this way each cell has a top, left, right, and bottom. If a "/" is in the cell, the top and left of that cell are connected, and right and bottom are connected. If a "\" is found, the top and right are connected, and the left and bottom are connected. If " " is found, the top, left, bottom, and right are connected. Each cell's edge is also connected to its neighbouring cell's edge (eg. a cells top edge is connected to the above cell's bottom edge). I made an adjacency list of these connections, and then ran union find on them.
    Similar to you, although my solution worked it didn't rank very high in either time or space metrics.

    • @qulinxao
      @qulinxao 4 місяці тому

      class Solution:
      def regionsBySlashes(self, g: List[str]) -> int:
      n,c,d=len(g),0,[[-1,0],[0,1],[1,0],[0,-1]]
      a=[[[0]*4 for _ in range(n)]for _ in range(n)]
      b={ '/':[[3],[2],[1],[0]],
      '\\':[[1],[0],[3],[2]],
      ' ':[[1,3],[0,2],[1,3],[0,2]]}
      def f(y,x,z):
      if 0

    • @corrogist692
      @corrogist692 4 місяці тому

      Same way as I did it. But I did not create an extra adj list, coz u can find the indices of elements in the "parent" to join directly while iterating through the grid.

    • @33galactus
      @33galactus 4 місяці тому +1

      Great approach! But you don't have to separately create an adjacency list of these connections, just look for neighboring elements of the cell based on your diagram. Also, you can solve it using simple dfs as well (i.e. without union-find).

    • @jamestwosheep
      @jamestwosheep 4 місяці тому

      @@corrogist692 That's a very good point about the need to not have an adjacency list, and I'm a little embarrassed that I didn't think of that. Thank you for pointing that out to me!

    • @jamestwosheep
      @jamestwosheep 4 місяці тому

      @@33galactus That's a very good point about the adjacency list being unnecessary, I honestly can't believe I didn't think of it. 😅
      You're right that a DFS would have been more straightforward than a union find, too. I'm trying to get a little more practice implementing the latter, so that's the main reason I had opted for it. 🙂

  • @anthonya880
    @anthonya880 4 місяці тому +5

    Has this channel covered the Grind 75 list ?

  • @akinhwan
    @akinhwan 4 місяці тому

    you're killing it Neet, thanks for the daily consistency you push us to be better daily as well

  • @VipulMadan31
    @VipulMadan31 4 місяці тому +5

    I am not able to see the intuition behind scaling every block to 3x3 matrix, I mean how do you think of it? Is this some important concept which I am missing out on?

    • @avneetsingh6194
      @avneetsingh6194 4 місяці тому +1

      It's pretty hard to come up with this unless u have seen this so don't be sad u r not alone

    • @VipulMadan31
      @VipulMadan31 4 місяці тому

      @@avneetsingh6194 ok, thanks bro

    • @AakashKumar-vf3dh
      @AakashKumar-vf3dh 4 місяці тому +1

      I feel it is more intuitive to come up with DSU than this approach.

    • @VipulMadan31
      @VipulMadan31 4 місяці тому

      @@AakashKumar-vf3dh Even i feel the same brother, if you have coded your DSU implementation, please share it, i am not able to think of how to implement it...

  • @ec8483
    @ec8483 4 місяці тому

    Using disjoint set is the most efficient way to this question, but DFS is more general.

  • @yang5843
    @yang5843 4 місяці тому

    That's why Neetcode is the goat!

  • @satviksrinivas8764
    @satviksrinivas8764 4 місяці тому +2

    Damn, this is a really good problem.

  • @MP-ny3ep
    @MP-ny3ep 4 місяці тому +1

    Thank you , another great explanation!

  • @MadpolygonDEV
    @MadpolygonDEV 4 місяці тому +12

    First comment. Remember to take breaks champ ❤ We all owe you our sanity

  • @SuchismitaDeb-h7l
    @SuchismitaDeb-h7l 4 місяці тому +1

    Hello Everyone,
    Kindly share some similar practice list like this problem.
    Kind of new type of upgrading the grid.

  • @rajveersingh95
    @rajveersingh95 4 місяці тому

    i did the 2*2 square for each 1*1 and quickly found out 😅. then thought of the diagonals and immediately realised that my 1s were blocking some diagonals but not others. that is when I thought I need to follow corner to corner paths with the slashes but then I couldn't come up with an idea to avoid double counting and I knew it was time for neetcode

    • @rajveersingh95
      @rajveersingh95 4 місяці тому

      PS : if you declare the matrix element as bool and declare empty as false and block as true, you won't need a separate visited matrix.

  • @grandmasterofthrow6238
    @grandmasterofthrow6238 4 місяці тому

    This solution is f'in genius! 🤯

  • @hithambasheir3283
    @hithambasheir3283 4 місяці тому

    Now we're getting in computer vision stuff!

  • @ameyakhotofficial
    @ameyakhotofficial 4 місяці тому

    UA-cam video inside a youtube video. Now that's recursion folks!

  • @rostislav_engineer
    @rostislav_engineer 4 місяці тому

    thanks neetcode! visited set is a bit redundant, we better just mark cell as 1

  • @DeathSugar
    @DeathSugar 4 місяці тому

    you made grid2 so you could just paint over it instead of allocating visit. it would more memory efficient

  • @swastiktiwari7066
    @swastiktiwari7066 4 місяці тому +2

    I think the visited set is not needed as the newly constructed grid can be modified during each run of dfs such that all reachable 0 doing a run of dfs are marked as 1. eg.
    class Solution:
    def regionsBySlashes(self, grid: List[str]) -> int:
    m,n = len(grid),len(grid[0])
    M,N = 3*m,3*n
    grid1 = [[0]*N for _ in range(M)]
    directions = [[-1,0],[1,0],[0,-1],[0,1]]
    res = 0
    for i in range(m):
    for j in range(n):
    if grid[i][j] == '/':
    i1,j1 = 3*i,3*j
    grid1[i1][j1+2] = 1
    grid1[i1+1][j1+1] = 1
    grid1[i1+2][j1] = 1
    elif grid[i][j] == '\\':
    i1,j1 = 3*i,3*j
    grid1[i1][j1] = 1
    grid1[i1+1][j1+1] = 1
    grid1[i1+2][j1+2] = 1
    def dfs(r,c):
    if r in [-1,M] or c in [-1,N] or grid1[r][c] == 1: return
    grid1[r][c] = 1
    for dx,dy in directions: dfs(r+dx,c+dy)
    for i in range(M):
    for j in range(N):
    if grid1[i][j] == 0:
    dfs(i,j)
    res+=1
    return res

    • @33galactus
      @33galactus 4 місяці тому +2

      Agree. But it will not improve overall space complexity.

    • @afsalts5872
      @afsalts5872 4 місяці тому

      Y​@@33galactus

    • @33galactus
      @33galactus 4 місяці тому

      @@afsalts5872 Newly constructed grid takes O(rows*cols) space, therefore removing visited set will not affect space complexity. Even if you don't construct a new grid array (let's say in problems like number of islands) your space complexity is still O(rows*cols) because of the implicit recurisive stack of the dfs function.

  • @IK-xk7ex
    @IK-xk7ex 4 місяці тому +2

    Why don't you store visited cells in scaled array? Mark 1 for visited, -1 - barrier, 0 - not visited. Like optimisation

    • @greatfate
      @greatfate 4 місяці тому +1

      you can even treat visited and barriers as the same thing, then it's just a boolean array

  • @milktea2755
    @milktea2755 3 місяці тому

    Is there any reason we pass in the visit set as a parameter to DFS as opposed to adding to a global visit set? Thank you!

  • @Techky-y5f
    @Techky-y5f 4 місяці тому

    I really like your videos , Full support from India

  • @chaitanyayeole4111
    @chaitanyayeole4111 4 місяці тому

    Can you please make a video on Maximum Value at a Given Index in a Bounded Array | Leetcode - 1802?

  • @ravikumar4870
    @ravikumar4870 4 місяці тому

    Amazing explanation...❤

  • @ahmedtremo
    @ahmedtremo 4 місяці тому

    great explanation as usual

  • @BigParmChannel
    @BigParmChannel 4 місяці тому

    This problem really made me want to learn DSA again. 💀

  • @VrajRana-p4y
    @VrajRana-p4y 4 місяці тому

    Okay, I have solved few hard problems which are easier than this, I didn't had any idea what to do. I have Google Interview, if this would be asked I doomed(not now of course).

  • @mehekswe
    @mehekswe 4 місяці тому

    Instead of using visit set, using the same enlarged grid and marking visited cells with 2 is better

  • @amol_
    @amol_ 4 місяці тому

    Did you come up to idea about scaling yourself ? or did you use any hint ?
    Actually even coming to idea about scaling for two, how one will get idea to go for three times ?

  • @user-tt3lb1yy6i
    @user-tt3lb1yy6i 4 місяці тому

    Shouldn't "grid2[r][c] != 0" in the dfs function create an index out of range error?

  • @chaitanyayeole4111
    @chaitanyayeole4111 4 місяці тому

    Can you please make a video on Leetcode 2145 Count the Hidden Sequences?
    I am not able to understand how to tackle prefix sum questions.

  • @qulinxao
    @qulinxao 4 місяці тому

    exist OUT of THE BOX solution: with standard flood fill
    build around input square square with doubled square and ROTATE it in 45gradus then standard floodfill for counting

  • @DNKF
    @DNKF 4 місяці тому

    Could you please also explain how Union Find works on this question? Thanks!

  • @anukulsahu
    @anukulsahu 4 місяці тому

    How do you think so, u r so good at what ur work, thats y , eyeglasses are thicker 😄

  • @LeoLawrence-b7u
    @LeoLawrence-b7u 4 місяці тому

    Can we implement the Union - Find algorithm here ?

  • @laveshbhandari9719
    @laveshbhandari9719 4 місяці тому

    Brilliant!!

  • @Antinormanisto
    @Antinormanisto 4 місяці тому +2

    Why mine is TLE ???😭😭😭
    class Solution:
    def regionsBySlashes(self, grid: List[str]) -> int:
    # 1. transform grid into grid of 1 and 0
    total = 0
    n = len(grid)
    s = n * 3
    square = [[0] * s for _ in range(s)]
    for i in range(n):
    for j in range(n):
    char = grid[i][j]
    if char == '/':
    ii, jj = i * 3, j * 3 + 2
    square[ii][jj] = 1
    square[ii + 1][jj - 1] = 1
    square[ii + 2][jj - 2] = 1
    elif char == '\\':
    ii, jj = i * 3, j * 3
    square[ii][jj] = 1
    square[ii + 1][jj + 1] = 1
    square[ii + 2][jj + 2] = 1
    # 2. 200. number of islands
    deq = collections.deque()
    visited = set()
    for i in range(s):
    for j in range(s):
    if square[i][j] == 0:
    total += 1
    deq.append((i, j))
    while deq:
    r, c = deq.popleft()
    if square[r][c] == 0:
    square[r][c] = 1
    visited.add((r, c))
    if 0

    • @Antinormanisto
      @Antinormanisto 4 місяці тому

      I just did it with dfs and it works.. Are functions faster than iterative solutions!?

    • @LiuGang
      @LiuGang 4 місяці тому +1

      # Two reasons : 1) visited is redundant, can be removed. 2) mark a reachable cell as visited (square[*][*]=1) when append it to deq can speed up BFS. Here is my modified version:
      class Solution:
      def regionsBySlashes(self, grid: List[str]) -> int:
      # 1. transform grid into grid of 1 and 0
      total = 0
      n = len(grid)
      s = n * 3
      square = [[0] * s for _ in range(s)]
      for i in range(n):
      for j in range(n):
      char = grid[i][j]
      if char == '/':
      ii, jj = i * 3, j * 3 + 2
      square[ii][jj] = 1
      square[ii + 1][jj - 1] = 1
      square[ii + 2][jj - 2] = 1
      elif char == '\\':
      ii, jj = i * 3, j * 3
      square[ii][jj] = 1
      square[ii + 1][jj + 1] = 1
      square[ii + 2][jj + 2] = 1
      def bfs(i,j):
      deq = collections.deque()
      deq.append((i, j))
      square[i][j] = 1

      while deq:
      r, c = deq.popleft()
      for nr,nc in [ [r-1, c], [r+1, c], [r, c-1], [r, c+1]]:
      if 0

  • @corrogist692
    @corrogist692 4 місяці тому +1

    I chopped every 1x1 to four parts then implemented union-find to join them...lol

    • @lavanya_m01
      @lavanya_m01 4 місяці тому

      Can u pls show the code

    • @corrogist692
      @corrogist692 4 місяці тому

      @@lavanya_m01 I apologise for my long ass code lol
      ```python
      class Solution:
      def regionsBySlashes(self, grid: List[str]) -> int:
      #initalize parent & size array : 4*row*col, separating every small 1x1 square to TOP(1), LEFT(2), RIGHT(3), BOTTOM(4)
      row=len(grid)
      col=len(grid[0])
      self.parent=[i for i in range(4*row*col)]
      self.size=[1 for i in range(4*row*col)]
      #Implement Union-Find
      def find(i):
      if i!=self.parent[i]:
      self.parent[i]=find(self.parent[i])
      return self.parent[i]

      def union(x, y):
      px, py= find(x),find(y)
      if px==py:
      return
      if self.size[px]

    • @corrogist692
      @corrogist692 4 місяці тому

      @@lavanya_m01 but it is quite a standard implementation, many lines but the only tricky part is to sort out the indices

  • @ElegantHumanoid
    @ElegantHumanoid 4 місяці тому

    Is there any particular reason you avoided using union find and euler's formula as a solution? I tried to understand it by myself but the solutions are mostly unclean and I couldn't understand them since I am not familiar with the language

    • @dan_____
      @dan_____ 4 місяці тому

      Personally I think the problem lends itself more to flood fill solutions. Disjointed sets and Euler's work but you have to perform a lot of setup in order to convert the initial problem into one that these two can solve.

  • @akashverma5756
    @akashverma5756 4 місяці тому

    It took me two hours to solve it. 30 mins for planning and writing code and 1.5 hours for debugging. 😂😂
    Initially, I scaled it to 2 x 2 grid instead of 3 x 3.

  • @tagoreraokosireddy529
    @tagoreraokosireddy529 4 місяці тому

    Would anyone mind explaining where did the ROWS and COLS defined which are used in dfs function

  • @suranjankarmakar8010
    @suranjankarmakar8010 4 місяці тому

    great

  • @31redorange08
    @31redorange08 4 місяці тому

    Are these live streams or why doesn't he look up the difference between slashes and backslashes?

  • @OmarAlimammadzade-v7s
    @OmarAlimammadzade-v7s 4 місяці тому +1

    can't we make grid2[r][c] = 1 instead of adding them to the set?

    • @NeetCodeIO
      @NeetCodeIO  4 місяці тому +1

      Yeah that's right, I'm just used to not modifying the input but in this case it doesn't matter

    • @abdulamaan4784
      @abdulamaan4784 4 місяці тому

      @@NeetCodeIO bro i thought this was a very small change, but it just shot me from 5% best runtime to 84% best runtime XD c++, i guess the thing pulling me back was the dynamic memory allocation stuff that set in c++ does when u push a new element to it, they are indeed very costly XD

  • @aashishbathe
    @aashishbathe 4 місяці тому

    ROWS1 and COLS1 would be same and equal to n, so no need for 2 declarations right?

  • @pastori2672
    @pastori2672 4 місяці тому

    union find is weakness 😭

  • @JamesBond-mq7pd
    @JamesBond-mq7pd 4 місяці тому

    How i am supposed to came up with this kind of solutions?

  • @dashdoom8452
    @dashdoom8452 4 місяці тому +1

    This has to be the worst problem on leetcode

  • @anuj_trehan
    @anuj_trehan 4 місяці тому +1

    Why only 3X3 ? Please help

    • @insertname6
      @insertname6 4 місяці тому +1

      Coz it just works ;-;

    • @lavanya_m01
      @lavanya_m01 4 місяці тому

      4:33 In 2x2 matrix, 4 directions gave wrong answers as we couldn't count the gaps correctly. But we couldn't use 8 directions (including diagonals) because it might cross the blocked path and reach the next region. To solve this issue, we use 3x3 matrix so that we could just use 4 directions and cover all the gaps correctly.

    • @debangshudey5515
      @debangshudey5515 4 місяці тому

      6:32 When you see in 2X2 matrix it has less squares around the current square so it cannot travel as diagonal traversal is not applicable in DFS but if we take 3X3 matrix then we get extra squares around so DFS is possible and it counts all the squares as 1 region and not separate regions.

  • @DNKF
    @DNKF 4 місяці тому +2

    First!

  • @Oorgitasur
    @Oorgitasur 4 місяці тому

    was this the first face reveal video

  • @jashanswork
    @jashanswork 3 місяці тому

    i should have iq of einstein to solve this problem i would've never thought to
    connect this to the no of islands problem

  • @ganeshc2793
    @ganeshc2793 4 місяці тому +4

    I don't get it why we should use 3*3

    • @debangshudey5515
      @debangshudey5515 4 місяці тому

      6:32 When you see in 2X2 matrix it has less squares around the current square so it cannot travel as diagonal traversal is not applicable in DFS but if we take 3X3 matrix then we get extra squares around so DFS is possible and it counts all the squares as 1 region and not separate regions.

  • @Kv-kk2nj
    @Kv-kk2nj 4 місяці тому

    Why !!!
    Are they needed

  • @light2666
    @light2666 4 місяці тому

    I did come up with this solution but I thought it would TLE so gave up

  • @venkateshnaidu2133
    @venkateshnaidu2133 4 місяці тому

    🤯

  • @user-my6yf1st8z
    @user-my6yf1st8z 4 місяці тому +3

    do you guys really understand the explanation?

    • @ShinAkuma
      @ShinAkuma 4 місяці тому +3

      nope. The problem statement is the most confusing I've ever come across. I usually just ignore these kinds of problems since the chances of facing something like this in an interview are low.

    • @rambabupatidar3092
      @rambabupatidar3092 4 місяці тому

      Use pen papers to draw out some matrix you will get it, initially it seems overwhelming

    • @ShinAkuma
      @ShinAkuma 4 місяці тому

      @@rambabupatidar3092 Draw matrix how ?
      The problem says it's a nxn matrix, but we're instead given a single dimension array of strings.
      How does this [" /" , "/ "] translate to a matrix ?

    • @pranavsharma7479
      @pranavsharma7479 4 місяці тому

      I didn't get it at all , i am here just to know what the crap it wants

    • @NeetCodeIO
      @NeetCodeIO  4 місяці тому +2

      Is there anything specific that was confusing?
      If you're not familiar with graph traversals, and havent solved a problem like Number of Islands, then I probably wouldn't attempt this problem yet.
      Otherwise, this one isnt too bad after the scaling part.

  • @blipbloping
    @blipbloping 4 місяці тому +1

    how tf

  • @_sf_editz1870
    @_sf_editz1870 4 місяці тому

    How can you even come up with that bruhhh ?? anyway java code : class Solution {
    public int regionsBySlashes(String[] grid) {
    //0 means free 1 means blocked
    int rows = grid.length;
    int cols = grid[0].length();
    int largeRows = rows*3;
    int largeCols = cols*3;
    int lmx[][] = new int[largeRows][largeCols];
    for(int i=0; i

  • @Alexander-zt9kz
    @Alexander-zt9kz 4 місяці тому

    Wtf

  • @anurag7782
    @anurag7782 4 місяці тому

    Your intro gives me motion sickness