classSolution(object): defnumIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ ifnot grid ornot grid[0]: return0 M, N = len(grid), len(grid[0]) que = collections.deque() res = 0 directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] for i in range(M): for j in range(N): if grid[i][j] == '1': res += 1 grid[i][j] = '0' que.append((i, j)) while que: x, y = que.pop() for d in directions: nx, ny = x + d[0], y + d[1] if0 <= nx < M and0 <= ny < N and grid[nx][ny] == '1': grid[nx][ny] = '0' que.append((nx, ny)) return res
classSolution(object): defisValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ # 注意:这里不能用[[False]*9]*9来初始化,牵涉到深浅拷贝的问题 row = [[Falsefor i in range(9)] for j in range(9)] col = [[Falsefor i in range(9)] for j in range(9)] block = [[Falsefor i in range(9)] for j in range(9)] for i in range(9): for j in range(9): if board[i][j] != '.': num = int(board[i][j]) - 1 k = i/3*3 + j/3 if row[i][num] or col[j][num] or block[k][num]: returnFalse row[i][num] = col[j][num] = block[k][num] = True returnTrue