标签:
1. 把所有与边界联通的"O"替换成别的字符,比如"#"
2. 把剩下的所有"O"替换成"X"
3. 把所有与边界联通的"#"替换成"X"
代码:
1 void replace(vector<vector<char> > &board, int i, int j, char before, char after) { 2 stack<pair<int, int> > st; 3 int rlen = board.size(); 4 int clen = board[0].size(); 5 int rnext[4] = {-1, 1, 0, 0}; 6 int cnext[4] = {0, 0, -1, 1}; 7 8 st.push(pair<int, int>(i, j)); 9 while (!st.empty()) { 10 pair<int, int> top = st.top(); 11 st.pop(); 12 if (top.first < 0 || top.first >= rlen || top.second < 0 || top.second >= clen || board[top.first][top.second] != before) 13 continue; 14 board[top.first][top.second] = after; 15 for (int k = 0; k < 4; k++) 16 st.push(pair<int, int>(top.first + rnext[k], top.second + cnext[k])); 17 } 18 } 19 20 void solve(vector<vector<char>> &board) { 21 if (board.empty() || board[0].empty()) return; 22 int rlen = board.size(); 23 int clen = board[0].size(); 24 25 for (int i = 0; i < rlen; i++) { 26 replace(board, i, 0, ‘O‘, ‘#‘); 27 replace(board, i, clen - 1, ‘O‘, ‘#‘); 28 } 29 for (int j = 0; j < clen; j++) { 30 replace(board, 0, j, ‘O‘, ‘#‘); 31 replace(board, rlen - 1, j, ‘O‘, ‘#‘); 32 } 33 34 for (int i = 1; i < rlen - 1; i++) 35 for (int j = 1; j < clen - 1; j++) 36 if (board[i][j] == ‘O‘) 37 board[i][j] = ‘X‘; 38 39 for (int i = 0; i < rlen; i++) { 40 replace(board, i, 0, ‘#‘, ‘O‘); 41 replace(board, i, clen - 1, ‘#‘, ‘O‘); 42 } 43 for (int j = 0; j < clen; j++) { 44 replace(board, 0, j, ‘#‘, ‘O‘); 45 replace(board, rlen - 1, j, ‘#‘, ‘O‘); 46 } 47 }
一开始是用递归去替换,结果爆栈了(Runtime error),只好老老实实用栈。。
Leetcode#130 Surrounded Regions
标签:
原文地址:http://www.cnblogs.com/boring09/p/4246180.html