将内部的O点变成X
input
X X X X
X O O X
X X O X
X O X X
output
X X X X
X X X X
X X X X
X O X X
DFS图所有边上的点,将边上的O以及其联通域变为T,然后将内部的O变为X,外部的T变为O,本质是种子填充算法。
此题对于is_in这个函数要注意, 不要用(x < m) && (x >= 0) && (y < n) && (y >= 0) 会堆栈溢出!!原因是会出现边上的点全是O。。。
1 class Solution { 2 public: 3 4 int m, n; 5 bool is_in(int x, int y) 6 { 7 return (x < m-1) && (x >= 1) && (y < n-1) && (y >= 1); 8 } 9 10 void dfs(std::vector<std::vector<char>> &board,int x,int y) 11 { 12 //if (!(is_in(x, y) && board[x][y] == ‘O‘)) return; 13 //printf("%d %d\n", x, y); 14 board[x][y] = ‘T‘; 15 int dir[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; 16 for (int i = 0; i < 4; ++i){ 17 int tx = x + dir[i][0]; 18 int ty = y + dir[i][1]; 19 if (is_in(tx, ty) && board[tx][ty] == ‘O‘) 20 { 21 dfs(board, tx, ty); 22 } 23 } 24 } 25 26 void change(std::vector<std::vector<char>> &board) 27 { 28 for (int i = 0; i < m;++i){ 29 for (int j = 0; j < n;++j){ 30 if (board[i][j] == ‘T‘) board[i][j] = ‘O‘; 31 else if (board[i][j] == ‘O‘) board[i][j] = ‘X‘; 32 else; 33 } 34 } 35 } 36 37 void solve(std::vector<std::vector<char>> &board)
{ 38 m = board.size(); 39 if (m == 0) return; 40 n = board[0].size(); 41 if (n == 0) return; 42 for (int i = 0; i < m;++i){ 43 if (board[i][0] == ‘O‘) dfs(board, i, 0); 44 if (board[i][n - 1] == ‘O‘) dfs(board, i, n-1); 45 } 46 for (int i = 0; i < n; ++i){ 47 if (board[0][i] == ‘O‘) dfs(board, 0, i); 48 if (board[m-1][i] == ‘O‘) dfs(board, m-1, i); 49 } 50 change(board); 51 } 52 };
Leetcode 130 Surrounded Regions DFS
原文:http://www.cnblogs.com/onlyac/p/5132661.html