Test case error ? Python

  • 3
    class Solution:
    # @param grid, a list of list of characters
    # @return an integer
    def numIslands(self, grid):
        if not grid: return 0
        m = len(grid)
        n = len(grid[0])
        result = 0
        for i in xrange(m):
            for j in xrange(n):
                if grid[i][j] == '1':
                    result += 1
                    self.dfs(grid, i, j)
        return result 
    def dfs(self, grid, i, j):
        row = len(grid)
        cal = len(grid[0])
        grid[i][j] = '0'  
        if i > 0 and grid[i-1][j] == '1':
            self.dfs(grid, i-1, j)
        if i < row-1 and grid[i+1][j] == '1':
            self.dfs(grid, i+1, j)
        if j > 0 and grid[i][j-1] == '1':
            self.dfs(grid, i, j-1)
        if j < cal-1 and grid[i][j+1] == '1':
            self.dfs(grid, i, j+1)

    In the above solution, the test result is:
    " Runtime Error Message: Line 21: TypeError: 'str' object does not support item assignment
    Last executed input: ["1"]"
    But actually the grid is the list of list, which is mutable, we could change the element in it. Why here it return the error said immutable ?

  • -1
    This post is deleted!

  • 0

    I think it's error of python test case. Because all other language tests use 2D-Array.

  • 0

    Yes, the same assignment for the "Surrounded Regions" has passed, that one use 2D-Array.

  • 0

    Sorry, I had just fixed this issue, now your solution should AC. The input type should be the same as "Surrounded Regions".

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.