一天一道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. c++ Lambda表达式待修改

    C++11引入了lambda表达式,使得程序员可以定义匿名函数,该函数是一次性执行的,既方便了编程,又能防止别人的访问. Lambda表达式的语法通过下图来介绍: 这里假设我们定义了一个如上图的lam ...

  2. 毕业回馈-89c51之定时器/计数器(Timer/Count)

    今天分享的是89c51系列单片机的内部资源定时器/计数器,在所有的嵌入式系统中都包含这两个内部功能. 首先先了解几个定时器/计数器相关的概念: •时钟周期:时钟周期 T 是时序中最小的时间单位,具体计 ...

  3. C++框架_之Qt的窗口部件系统的详解-上

    C++框架_之Qt的窗口部件系统的详解-上 第一部分概述 第一次建立helloworld程序时,曾看到Qt Creator提供的默认基类只有QMainWindow.QWidget和QDialog三种. ...

  4. Java语言程序设计课程学期总结

    2016-2017 第2学期 课程介绍 编程类课程,76学时(44理论+32实验),学期末还有1周的课程设计. 问题与现状 4个班共120人,教师无法逐一检查每个学生的编程实验. 纸质作业质量不高. ...

  5. Bootstrap3 栅格系统-实例:从堆叠到水平排列

    使用单一的一组 .col-md-* 栅格类,就可以创建一个基本的栅格系统,在手机和平板设备上一开始是堆叠在一起的(超小屏幕到小屏幕这一范围),在桌面(中等)屏幕设备上变为水平排列.所有"列( ...

  6. 搜索引擎solr和elasticsearch

    刚开始接触搜索引擎,网上收集了一些资料,在这里整理了一下分享给大家. 一.关于搜索引擎 搜索引擎(Search Engine)是指根据一定的策略.运用特定的计算机程序从互联网上搜集信息,在对信息进行组 ...

  7. 预处理指令--C语言

    ANSI标准C还定义了如下几个宏: __LINE__ 表示正在编译的文件的行号 __FILE__ 表示正在编译的文件的名字 __DATE__ 表示编译时刻的日期字符串,例如:"25 Dec ...

  8. Android简易实战教程--第四十七话《使用OKhttp回调方式获取网络信息》

    在之前的小案例中写过一篇使用HttpUrlConnection获取网络数据的例子.在OKhttp盛行的时代,当然要学会怎么使用它,本篇就对其基本使用做一个介绍,然后再使用它的接口回调的方式获取相同的数 ...

  9. RxJava(十一)defer操作符实现代码支持链式调用

    欢迎转载,转载请标明出处: http://blog.csdn.net/johnny901114/article/details/52597643 本文出自:[余志强的博客] 一.前言 现在越来越多An ...

  10. ObjectOutputStream 和 ObjectInputStream的使用

    一.看一下API文档 ObjectOutputStream : ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream.可以使用 ObjectInp ...