【转载】【leetcode】Surrounded regions
2013-09-18 17:34
211 查看
Surrounded regions
题意:假设一个二维图由X和O组成,将所有被X围住的O转换成X如:XXXX
XOOX
XXOX
XOXX
变成:XXXX
XXXX
XXXX
XOXX
思路:从O处开始BFS,用一个队列记录遍历的路径,如果这条路径都是在边界以内,没有超出边界,则将路径上所有的O变成X
代码:
void solve(vector<vector<char>> &board) {
// Start typing your C/C++ solution below // DO NOT write int main() function int N = board.size(); if (N == 0) return; int M = board[0].size(); if (M == 0) return; vector<vector<bool> > mark(N, vector<bool>(M, false)); int dx[4] = {-1, 1, 0, 0};//上下左右四个方向 int dy[4] = {0, 0, -1, 1}; for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { if (!mark[i][j] && board[i][j] == 'O') { vector<int> queX, queY;//遍历路径 queX.push_back(i); queY.push_back(j); mark[i][j] = true; int head = 0; bool result = !(i == 0 || j == 0 || i == N - 1 || j == M - 1) ;//是否在边界以内 while (head < queX.size()) { int nx = queX[head]; int ny = queY[head]; head++; for (int i = 0; i < 4; i++) { int nextX = nx + dx[i]; int nextY = ny + dy[i]; if (nextX >= 0 && nextX < N && nextY >= 0 && nextY < M) { if (!mark[nextX][nextY] && board[nextX][nextY] == 'O') { mark[nextX][nextY] = true; queX.push_back(nextX); queY.push_back(nextY); if (nextX == 0 || nextY == 0 || nextX == N - 1 || nextY == M - 1) //遍历到了边界 result = false; } } } } if (result) { for (int i = 0; i < queX.size(); i++) board[queX[i]][queY[i]] = 'X'; } } } }
相关文章推荐
- Leetcode 编程训练(转载)
- [转载]LeetCode: Gray Code
- 【LeetCode】Sqrt(x) (转载)
- 转载:LeetCode:5Longest Palindromic Substring 最长回文子串
- 【转载】LeetCode 题目总结/分类
- 【转载】【leetcode】Longest Substring Without Repeating Characters
- LeetCode 题目总结/分类(转载,做了一些标记)
- 【转载】【leetcode】Median of Two Sorted Arrays
- 【转载】【leetcode】题目分布
- 【转载】【leetcode】Gray Code
- Leetcode高频题频率表(转载)
- 【转载】leetcode中的backtracking
- 使用 CXF 做 webservice 简单例子(转载)
- 【转载】SSD 下的 MySQL IO 优化
- leetcode 278: First Bad Version
- Leetcode | Binary Tree Inorder Traversal
- Leetcode 34. Search for a Range
- leetcode_middle_94_106. Construct Binary Tree from Inorder and Postorder Traversal
- Add Two Numbers leetcode
- LeetCode 553. Optimal Division (除法划分,算法)