题目来源:
https://leetcode.com/problems/surrounded-regions/
题意分析:
给定给一个二维的板,这个板只包括‘X’和‘O’。将被‘X’包围的‘O’变成‘X’。比如:
X X X X X O O X X X O X X O X X
得到:
X X X X X X X X X X X X X O X X
题目思路:
从板的周围出发,从周围的‘O’出发深度搜索,能搜到的‘O’用visit记录他有没有访问过。最后将所有没有visit过的'O'变成‘X’.
代码(python):
1 class Solution(object): 2 def solve(self, board): 3 """ 4 :type board: List[List[str]] 5 :rtype: void Do not return anything, modify board in-place instead. 6 """ 7 m = len(board) 8 if m == 0: 9 return 10 n = len(board[0]) 11 visit = [[False for i in range(n)] for j in range(m)] 12 def dfs(i,j): 13 q = [] 14 q.append([i,j]) 15 while len(q) != 0: 16 tmp = q[0] 17 #print(tmp,visit[3][1],board[3][1]) 18 q.pop(0) 19 #down,up,left,right 20 if tmp[0] - 1 > 0 and board[tmp[0] - 1][tmp[1]] == 'O' and visit[tmp[0]-1][tmp[1]] == False: 21 visit[tmp[0] -1][tmp[1]] = True 22 q.append([tmp[0] - 1,tmp[1]]) 23 if tmp[0] + 1 < m and board[tmp[0] + 1][tmp[1]] == 'O' and visit[tmp[0]+1][tmp[1]] == False: 24 visit[tmp[0] +1][tmp[1]] = True 25 q.append([tmp[0] + 1,tmp[1]]) 26 if tmp[1] - 1 > 0 and board[tmp[0]][tmp[1] - 1] == 'O' and visit[tmp[0]][tmp[1]-1] == False: 27 visit[tmp[0]][tmp[1] - 1] = True 28 q.append([tmp[0],tmp[1] - 1]) 29 if tmp[1] + 1 < n and board[tmp[0]][tmp[1] + 1] == 'O' and visit[tmp[0]][tmp[1]+1] == False: 30 visit[tmp[0]][tmp[1]+1] = True 31 q.append([tmp[0],tmp[1]+1]) 32 for i in range(n): 33 if visit[0][i] == False and board[0][i] == 'O': 34 visit[0][i] = True 35 dfs(0,i) 36 if visit[m - 1][i] == False and board[m-1][i] == 'O': 37 visit[m-1][i] = True 38 dfs(m - 1,i) 39 for j in range(m): 40 if visit[j][0] == False and board[j][0] == 'O': 41 visit[j][0] = True 42 dfs(j,0) 43 if visit[j][n - 1] == False and board[j][n - 1] == 'O': 44 visit[j][n - 1] = True 45 dfs(j,n - 1) 46 for i in range(m): 47 for j in range(n): 48 if board[i][j] == 'O' and not visit[i][j]: 49 board[i][j] = 'X' 50 51