최대 1 분 소요

# using dfs...
# When you use 'method' defined in the class, you have to use 'self'
# like self.dfs(grid, i, j)
class Solution(object):
    def numIslands(self, grid):

        if not grid:
            return 0
        count = 0
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j]=='1':
                # By the condition, grid's elements are 'string'type.
                    self.dfs(grid, i, j)
                    count+=1
        return count
    def dfs(self, grid, i, j):
        if  i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j]!='1':
            return
      # the order is very "important". In that case, I had to check
      # the boundary at first. the checking contents is the last..
      # for avoiding indexing error. I had used some hours because of it...


        grid[i][j] = '#'
        self.dfs(grid, i+1, j)
        self.dfs(grid, i-1, j)
        self.dfs(grid, i, j+1)
        self.dfs(grid, i, j-1)

Summary

  1. When you use ‘method’ defined in the class, you have to use ‘self’ like self.dfs(grid, i, j)
  2. By the condition, grid’s elements are ‘string’type.(I have to read thoroughly)
  3. the order is very “important”. In that case, I had to check the boundary at first. the checking contents is the last..for avoiding indexing error. I had used some hours because of it…

댓글남기기