首页 > 代码库 > Leetcode#130 Surrounded Regions
Leetcode#130 Surrounded Regions
原题地址
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。