一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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

(二)解题

本题大意:棋盘上放满了‘X’和‘O’,将所有被‘X’包围的’O’全部转换成‘X’

需要注意被’X‘包围必须是上下左右都被包围。

这道题我最开始的做法是:遍历整个棋盘,当碰到一个’O‘之后,就采用广度搜索的方法,从上下左右四个方向上进行搜索,为’O‘就标记下来,如果搜索过程中碰到边界就代表此范围不能被’X‘包围,就不做处理;反之,如果没有碰到边界就把标记下来的’O‘全部转换成’X‘。

这种做法不好之处就是:需要找遍棋盘中所有的’O‘集合。

于是就采用逆向思维,从边界出发,已经判定这块’O’集合为不被’X‘包围的集合,这样就大大减少了搜索量。

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        if(board.empty()) return;
        int row = board.size();
        int col = board[0].size();
        for(int i = 0 ; i < row ; i++)//从左、右边界开始往里面搜
        {
            if(board[i][0]=='O') isSurroundendBy(board,row,col,i,0);
            if(board[i][col-1]=='O') isSurroundendBy(board,row,col,i,col-1);
        }
        for(int i = 1 ; i < col-1 ; i++)//从上、下边界开始往里面搜
        {
            if(board[0][i]=='O') isSurroundendBy(board,row,col,0,i);
            if(board[row-1][i]=='O') isSurroundendBy(board,row,col,row-1,i);
        }
        for(int i = 0 ; i < row ; i++)//遍历棋盘,将标记的’1‘还原成’O‘,将’O‘改写成’X‘
        {
            for(int j = 0 ; j < col ;j++)
            {
                if(board[i][j] == 'O') board[i][j] = 'X';
                else if(board[i][j] == '1') board[i][j] = 'O';
           }
        }
    }
    void isSurroundendBy(vector<vector<char>>& board, int& row, int& col, int i, int j)
    {
        if(board[i][j] =='O'){
            board[i][j] = '1';//标记需要修改的’O‘
                //上下左右四个方向搜索
            if (i+1<row&&board[i+1][j]=='O') isSurroundendBy(board, row, col, i+1, j);
            if (i-1>=0&&board[i-1][j]=='O') isSurroundendBy(board, row, col, i-1, j);
            if (j+1<col&&board[i][j+1]=='O') isSurroundendBy(board, row, col, i, j+1);
            if (j-1>=0&&board[i][j-1]=='O') isSurroundendBy(board, row, col, i, j-1);
        }
    }
};

于是兴高采烈的提交代码,结果Runtime Error!

递归的缺点显露出来了,递归深度太深,导致堆栈溢出。

接下来就把递归版本转换成迭代版本,消除递归带来的堆栈消耗。

class Solution {
public:
    void solve(vector<vector<char>>& board) {
        int row = board.size();
        if(row==0) return;
        int col = board[0].size();
        for(int i = 0 ; i < row ; i++)//从左、右边界开始往里面
        {
            if(board[i][0]=='O') isSurroundendBy(board,row,col,i,0);
            if(board[i][col-1]=='O') isSurroundendBy(board,row,col,i,col-1);//从上、下边界开始往里面
        }
        for(int i = 0 ; i < col ; i++)
        {
            if(board[0][i]=='O') isSurroundendBy(board,row,col,0,i);
            if(board[row-1][i]=='O') isSurroundendBy(board,row,col,row-1,i);
        }
        for (int i = 0; i < row; i++)//遍历棋盘修改标记
        {
            for (int j = 0; j < col; j++)
            {
                if (board[i][j] == 'O') board[i][j] = 'X';
                if (board[i][j] == '1') board[i][j] = 'O';
            }
        }
    }
    int X[4] = {-1,0,1,0};//四个方向
    int Y[4] = { 0,-1,0,1 };
    void isSurroundendBy(vector<vector<char>>& board, int& row, int& col, int i, int j)
    {
        stack<pair<int, int>> temp_stack;//用堆栈来存储中间变量
        temp_stack.push(make_pair(i, j));
        board[i][j] = '1';
        while (!temp_stack.empty())//堆栈不为空就代表没有处理完
        {
            int y = temp_stack.top().first;
            int x = temp_stack.top().second;
            temp_stack.pop();//出栈
            for (int idx = 0; idx < 4; idx++)//处理出栈坐标四个方向是否存在‘O’
            {
                int y0 = y + Y[idx];
                int x0 = x + X[idx];
                if (y0 >= 0 && y0 < row&&x0 >= 0 && x0 < col)
                {
                    if (board[y0][x0] == 'O')//为'O'就压栈等待后续处理
                    {
                        board[y0][x0] = '1';
                        temp_stack.push(make_pair(y0, x0));
                    }
                }
            }
        }
    }
};

提交代码,AC,16ms!

更多关于递归和迭代的转换可以参考本人的这篇博文:【数据结构与算法】深入浅出递归和迭代的通用转换思想

【一天一道LeetCode】#130. Surrounded Regions的更多相关文章

  1. [LeetCode] 130. Surrounded Regions 包围区域

    Given a 2D board containing 'X' and 'O'(the letter O), capture all regions surrounded by 'X'. A regi ...

  2. Leetcode 130. Surrounded Regions

    Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A reg ...

  3. Java for LeetCode 130 Surrounded Regions

    Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured ...

  4. leetcode 130 Surrounded Regions(BFS)

    Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured ...

  5. Leetcode 130 Surrounded Regions DFS

    将内部的O点变成X input X X X XX O O X X X O XX O X X output X X X XX X X XX X X XX O X X DFS的基本框架是 void dfs ...

  6. leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions

    两种方式处理已经访问过的节点:一种是用visited存储已经访问过的1:另一种是通过改变原始数值的值,比如将1改成-1,这样小于等于0的都会停止. Number of Islands 用了第一种方式, ...

  7. 130. Surrounded Regions(M)

    130.Add to List 130. Surrounded Regions Given a 2D board containing 'X' and 'O' (the letter O), capt ...

  8. 【LeetCode】130. Surrounded Regions (2 solutions)

    Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A ...

  9. [LeetCode] 130. Surrounded Regions_Medium tag: DFS/BFS

    Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A reg ...

随机推荐

  1. CAP原理和BASE思想和ACID模型

    问题的解读 对于上面三个例子,相信大家一定看出来了,我们的终端用户在使用不同的计算机产品时对于数据一致性的需求是不一样的: 1.有些系统,既要快速地响应用户,同时还要保证系统的数据对于任意客户端都是真 ...

  2. django.db.utils.ProgrammingError: 1146 的解决办法

    在models中设置完数据库相关的东西后执行命令 python manage.py makemigrations 此处无错误 再次执行 python manage.py migrate 发生报错 错误 ...

  3. 解决linux中使用git,ssh每次都要输入密码

    在linux中使用git,去提交或者下载代码都是很方便的,但是最近新配置了一套系统,发现每次git pull或者其他动作都需要输入密码. 想一想不对劲啊,我使用的是ssh的方式clone的代码,而且在 ...

  4. C++并发高级接口:std::async和std::future

    std::async和std::future std::async创建一个后台线程执行传递的任务,这个任务只要是callable object均可,然后返回一个std::future.future储存 ...

  5. django的流程和命令行工具

    django实现流程django #安装: pip3 install django 添加环境变量 #1 创建project django-admin startproject mysite ---my ...

  6. Android 学习笔记一 自定义按钮背景图

    入门学到的一些组件都是比较规矩的,但在实际应用中,我们需要更多特色的组件,例如一个简单的Button,所以我们必须要自定义它的属性. 遇到的问题:用两张图片来代替按钮,分别表示点击前后 解决方法:用I ...

  7. Android自定义View(RollWeekView-炫酷的星期日期选择控件)

    转载请标明出处: http://blog.csdn.net/xmxkf/article/details/53420889 本文出自:[openXu的博客] 目录: 1分析 2定义控件布局 3定义Cus ...

  8. SpringBatch的核心组件JobLauncher和JobRepository

    Spring Batch的框架包括启动批处理作业的组件和存储Job执行产生的元数据.因此只需掌握配置这个基础框架在批处理应用程序中即启动Jobs并存储Job元数据. 组件:Job Launcher和J ...

  9. Device Mapper 代码分析

    Device Mapper(DM)是Linux 2.6全面引入的块设备新构架,通过DM可以灵活地管理系统中所有的真实或虚拟的块设备. DM以块设备的形式注册到Linux内核中,凡是挂载(或者说&quo ...

  10. 大数据基础知识问答----spark篇,大数据生态圈

    Spark相关知识点 1.Spark基础知识 1.Spark是什么? UCBerkeley AMPlab所开源的类HadoopMapReduce的通用的并行计算框架 dfsSpark基于mapredu ...