[LeetCode] Surrounded Regions(DFS、BFS)

Given a 2D board containing ‘X‘ and ‘O‘, capture all regions surrounded by ‘X‘.

A region is captured by flipping all ‘O‘s into ‘X‘s in that surrounded region.

For example,

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X
方法1DFS的Recursive实现,由于递归实现占用额外内存,当递归深度大时出现RunTime Error      思想是从board的外层四周开始,找到需要替换的‘O’先标记为‘V’,看此‘O’上下左右有没有需要替换的‘O’,不断深入。
  class Solution {
    public:
        typedef vector<vector<char> > BOARDTYPE;

        void solve(BOARDTYPE &board) {
            if (board.empty() || board[0].empty()) return;
            int N = board.size(), M = board[0].size();
            for (int i = 0; i < N; ++i)
                for (int j = 0; j < M; ++j)
                    if (i == 0 || j == 0 || i == N-1 || j == M-1)
                        dfs(board, i, j); // you may call dfs or bfs here!
            for (int i = 0; i < N; ++i)
                for (int j = 0; j < M; ++j)
                    board[i][j] = (board[i][j] == ‘V‘) ? ‘O‘ : ‘X‘;
        }

         void dfs(BOARDTYPE &board, int row, int col) {
            int N = board.size(), M = board[0].size();
            if (row < 0 || row >= N || col < 0 || col >= M) return;
            if (board[row][col] != ‘O‘) return;
            board[row][col] = ‘V‘;//把不需要更改的‘O’设为‘V’.
            dfs(board, row+1, col);
            dfs(board, row-1, col);
            dfs(board, row, col+1);
            dfs(board, row, col-1);
        }
    };

方法2DFS的stack实现

It pushes all neighbors into stack, and pick the top one, which is one of the neighbors just pushed in, and further gets its neighbors.

仔细考虑一下,这个乍一看很容易被认为是BFS的实现。

  class Solution {
    public:
        typedef vector<vector<char> > BOARDTYPE;

        void solve(BOARDTYPE &board) {
            if (board.empty() || board[0].empty()) return;
            int N = board.size(), M = board[0].size();
            for (int i = 0; i < N; ++i)
                for (int j = 0; j < M; ++j)
                    if (i == 0 || j == 0 || i == N-1 || j == M-1)
                        dfs(board, i, j); // you may call dfs or bfs here!
            for (int i = 0; i < N; ++i)
                for (int j = 0; j < M; ++j)
                    board[i][j] = (board[i][j] == ‘V‘) ? ‘O‘ : ‘X‘;
        }

         void dfs(BOARDTYPE &board, int row, int col) {
            int N = board.size(), M = board[0].size();
            if (row < 0 || row >= N || col < 0 || col >= M) return;
            if (board[row][col] != ‘O‘) return;
            stack<pair<int,int>> s;
            s.push(make_pair(row,col));
            board[row][col] = ‘V‘;//把不需要更改的‘O’设为‘V’.
            while(!s.empty()){
                row = s.top().first;
                col = s.top().second;
                s.pop();
                if(row+1<N && board[row+1][col]==‘O‘){
                    s.push(make_pair(row+1,col));
                    board[row+1][col]=‘V‘;
                }
                if(row-1>=0 && board[row-1][col]==‘O‘){
                    s.push(make_pair(row-1,col));
                    board[row-1][col]=‘V‘;
                }
                if(col+1<M && board[row][col+1]==‘O‘){
                    s.push(make_pair(row,col+1));
                    board[row][col+1]=‘V‘;
                }
                if(col-1<N && board[row][col-1]==‘O‘){
                    s.push(make_pair(row,col-1));
                    board[row][col-1]=‘V‘;
                }
            }//end while
        }
    };

方法3BFS的queue实现

 class Solution {
    public:
        typedef vector<vector<char> > BOARDTYPE;

        void solve(BOARDTYPE &board) {
            if (board.empty() || board[0].empty()) return;
            int N = board.size(), M = board[0].size();
            queue<pair<int,int>> q;

            for (int i = 0; i < N; ++i){
                if(board[i][M-1]==‘O‘ ){
                    q.push(make_pair(i,M-1));
                    board[i][M-1]=‘V‘;
                }
                if(board[i][0]==‘O‘){
                    q.push(make_pair(i,0));
                    board[i][0]=‘V‘;
                }
            }
            for (int j = 0; j < M; ++j){
                if(board[0][j]==‘O‘){
                    q.push(make_pair(0,j));
                    board[0][j]=‘V‘;
                }
                if( board[N-1][j]==‘O‘){
                    q.push(make_pair(N-1,j));
                    board[N-1][j]=‘V‘;
                }

            }
            bfs(board,q);
            for (int i = 0; i < N; ++i)
                for (int j = 0; j < M; ++j)
                    board[i][j] = (board[i][j] == ‘V‘) ? ‘O‘ : ‘X‘;
        }

         void bfs(BOARDTYPE &board, queue<pair<int,int>> &q) {
            int N = board.size(), M = board[0].size();

            while(!q.empty()){
                int row = q.front().first;
                int col = q.front().second;
                q.pop();

                if(row+1<N && board[row+1][col]==‘O‘){
                    q.push(make_pair(row+1,col));
                    board[row+1][col]=‘V‘;
                }
                if(row-1>=0 && board[row-1][col]==‘O‘){
                    q.push(make_pair(row-1,col));
                    board[row-1][col]=‘V‘;
                }
                if(col+1<M && board[row][col+1]==‘O‘){
                    q.push(make_pair(row,col+1));
                    board[row][col+1]=‘V‘;
                }
                if(col-1<N && board[row][col-1]==‘O‘){
                    q.push(make_pair(row,col-1));
                    board[row][col-1]=‘V‘;
                }
            }//end while
        }
    };

[LeetCode] Surrounded Regions(DFS、BFS)

时间: 2024-10-11 17:16:45

[LeetCode] Surrounded Regions(DFS、BFS)的相关文章

搜索分析(DFS、BFS、递归、记忆化搜索)

搜索分析(DFS.BFS.递归.记忆化搜索) 1.线性查找 在数组a[]={0,1,2,3,4,5,6,7,8,9,10}中查找1这个元素. (1)普通搜索方法,一个循环从0到10搜索,这里略. (2)递归(从中间向两边) 1 //递归一定要写成记忆化递归 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool vis[11]; 5 int count1=0; 6 7 void search(int n){ 8 count1++; 9

图的遍历 (dfs与bfs)x

遍历是很多图论算法的基础,所谓图的遍历( graph traversal),也称为搜索( search),就是从图中某个顶点出发,沿着一些边访遍图中所有的顶点,且使每个顶点仅被访问一次.         遍历可以采取两种方法进行:         深度优先搜索( DFS: depth first search):         广度优先搜索( BFS: breadth first search). 对图进行存储与遍历: 输入: 第一行:顶点数n. 第二行:边数m. 以下m行,每行两个顶点编号u

POJ 1426 Find The Multiple(DFS,BFS)

Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100

lightoj 1111 - Best Picnic Ever(dfs or bfs)

题目链接 http://www.lightoj.com/volume_showproblem.php?problem=1111 题意:给你一个有向图再给你几个人的位置,问所有人可以在哪些点相聚. 简单的搜索题,可以用bfs也可以用dfs,要注意的是存边的时候最好用vector,因为边比较少. 用struct会超时.下面附上dfs和bfs代码. #include <iostream> #include <cstring> #include <queue> #include

Leetcode拾萃(算法篇)——暴力破解(DFS、BFS、permutation)

引言 现在互联网的招工流程,算法题是必不可少的,对于像我这种没搞过ACM的吃瓜群众,好在有leetcode,拯救我于水火.于是乎,断断续续,刷了一些题,其中一些题还是值得细细品味的,现把一些问题整理一下,有些解法是我自己写的,也有些解法是参考了discuss中的答案,当做是秋招的一个小小总结.由于水平有限,代码写得并不好,选的题目也只能用于入门,希望大家见谅. 暴力破解 暴力破解,据我个人理解,就是遍历整棵搜索树,没有删繁就简,紧是单单的搜索和匹配. 1.基本暴力破解:对于最基本的暴力破解,就是

[LeetCode]130 Surrounded Regions(DFS)

题目链接:https://leetcode.com/problems/surrounded-regions/?tab=Description 题意:把非边界的O改成X. 先dfs边界的,打好标记.把没变的变成X后同时更新标记的为O. 1 class Solution { 2 public: 3 const int dx[5] = {0, 0, 1, -1}; 4 const int dy[5] = {1, -1, 0, 0}; 5 int n, m; 6 bool ok(int x, int y

LeetCode Number of Islands 岛的数量(DFS,BFS)

题意:0代表水,1代表陆地,那么被水围起来的就是岛了,给一个01矩阵,问有多少个岛? 思路:DFS还是比较短,实现了一下.如果一个点已经被遍历过了,那就将其置为0就行了,不要去搜0的. 1 class Solution { 2 public: 3 bool isok(vector<vector<char> >& grid,int x,int y) 4 { 5 return x>=0 && y>=0 && x<grid.siz

算法导论--图的遍历(DFS与BFS)

转载请注明出处:勿在浮沙筑高台http://blog.csdn.net/luoshixian099/article/details/51897538 图的遍历就是从图中的某个顶点出发,按某种方法对图中的所有顶点访问且仅访问一次.为了保证图中的顶点在遍历过程中仅访问一次,要为每一个顶点设置一个访问标志.通常有两种方法:深度优先搜索(DFS)和广度优先搜索(BFS).这两种算法对有向图与无向图均适用. 以下面无向图为例: 1.深度优先搜索(DFS) 基本步骤: 1.从图中某个顶点v0出发,首先访问v

C++实现图的搜索(DFS和BFS)

1 #include<iostream> 2 #include<stack> 3 4 #include<queue> 5 #define Max 20 6 using namespace std; 7 8 class Vertex 9 { 10 public: 11 Vertex(char lab) 12 { 13 Label=lab; 14 wasVisited=false; 15 } 16 public: 17 bool wasVisited; 18 char La