[LeetCode] Matrix 值修改系列,例题 Surrounded Regions,Set Matrix Zeroes
引言
Matrix内部的值修改严格来讲放在一个系列里不大合适,因为对于不同的问题,所用的算法和技巧可能完全不同,权且这样归类,以后需要时再拆分吧。
例题 1
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
class Solution {
public:
void solve(vector<vector<char>> &board) {
}
};
这道题的思路应该比较容易想到:
遍历最外层一圈,如果有O,就把其相邻的也设置为O。接着遍历全矩阵,把内层O置为X。
但是这样做的问题遍历全矩阵时,分不清遇到的O是内层还是外层。
因此改进的方法是遍历最外层时,将O及其相邻的字符都设为"Y"。遍历全矩阵时,把"O"设置为X,把"Y"设置回"O"。
寻找O的邻居时,用的自然是BFS。每遇到一个O,就通过BFS将它以及邻居设置为"Y"
代码:
class Solution {
struct Point{
int h;
int v;
Point(int vp, int hp) : v(vp), h(hp) {};
};
public:
void BFS(int startH, int startW, vector<vector<char>> &board, queue<Point> que){
while(!que.empty()) que.pop();
int W = board[].size(), H = board.size();
Point p(startH, startW);
que.push(p);
while(!que.empty()){
Point cur = que.front();
que.pop();
board[cur.v][cur.h] = 'Y';
for(int i = ; i < ; i++){ //扫描四个方向上的邻居
if((cur.v+addV[i]) < H
&& (cur.h+addH[i]) < W
&& (cur.v+addV[i]) >=
&& (cur.h+addH[i]) >=
&& board[cur.v+addV[i]][cur.h+addH[i]] == 'O'){
que.push(Point(cur.v+addV[i], cur.h+addH[i]));
}
}
}
} void solve(vector<vector<char>> &board) {
if(board.size() == || board[].size() == ) return;
int W = board[].size(), H = board.size();
queue<Point> que;
int i, j = ;
for(i = ; i < W; ++i){
if(board[][i] == 'O') BFS(, i, board, que);
if(H > && board[H-][i] == 'O') BFS(H-, i, board, que); //遇到'O',调用BFS
}
for(i = ; i < H; ++i){
if(board[i][] == 'O') BFS(i, , board, que);
if(W > && board[i][W-] == 'O') BFS(i, W-, board, que);
} for(i = ; i < H; ++i){ //再次遍历全数组
for(j = ; j < W; ++j){
if(board[i][j] == 'O') board[i][j] = 'X';
if(board[i][j] == 'Y') board[i][j] = 'O';
}
}
}
private:
int addV[] = {, , -, };
int addH[] = {, , , -};
};
这样提交上去,超时。
有什么办法可以缩短时间呢?回想思路可以发现:每次遇到O,我们都调用一次BFS,每一次调用BFS,都需要清空队列que,然后再push。
为什么不把所有的BFS并为一次呢?每次遇到O,我们只向队列que中push当前O所在的Point,最后调用一次BFS集中处理que,其效果是完全一样的,但是时间上却省去了每次清空队列的时间。
代码:
class Solution {
struct Point{
int h;
int v;
Point(int vp, int hp) : v(vp), h(hp) {};
};
public:
void solve(vector<vector<char>> &board) {
if(board.size() == || board[].size() == ) return;
int W = board[].size(), H = board.size();
queue<Point> que;
int i, j = ;
for(i = ; i < W; ++i){
if(board[][i] == 'O') que.push(Point(, i));
if(H > && board[H-][i] == 'O') que.push(Point(H-, i)); //遇到O,只push,不再调用BFS
}
for(i = ; i < H; ++i){
if(board[i][] == 'O') que.push(Point(i, ));
if(W > && board[i][W-] == 'O') que.push(Point(i, W-)); //遇到O,只push,不再调用BFS
}
while(!que.empty()){ //调用BFS
Point cur = que.front();
que.pop();
board[cur.v][cur.h] = 'Y';
for(int i = ; i < ; i++){
if((cur.v+addV[i]) < H
&& (cur.h+addH[i]) < W
&& (cur.v+addV[i]) >=
&& (cur.h+addH[i]) >=
&& board[cur.v+addV[i]][cur.h+addH[i]] == 'O'){
que.push(Point(cur.v+addV[i], cur.h+addH[i]));
}
}
} for(i = ; i < H; ++i){
for(j = ; j < W; ++j){
if(board[i][j] == 'O') board[i][j] = 'X';
if(board[i][j] == 'Y') board[i][j] = 'O';
}
}
}
private:
int addV[] = {, , -, };
int addH[] = {, , , -};
};
小结:
这种需要更改Matrix的值的题目,上面解法用到了很简单的技巧:“引入一个中间值 Y”,避免了混淆。
例题 2
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Could you devise a constant space solution?
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) { }
};
这道题的困难之处在于“需要空间复杂度为常量”
有了上一题的启发,我们可以将0所在的行和列都设置为别的值X,最后将所有X设置为0。
但是这样做的弱点在于:
1. 每个元素都要被访问 >= 2次 (那些和0同行同列的元素被访问大于2次,那些不和0同行同列的元素被访问了2次)。
2. 如果题目改成vector<vector<bool> >,这种解法就失效了,因为没有第三个值可以引入。
如果空间复杂度要求是O(m+n)的话,我们会申明两个数组,分别来记录需要设为0的行号和列号。
进一步,如果如果空间复杂度要求是O(1),我们虽然不能申明新数组,但是我们能用第一行和第一列来标记那些需要置为0的行和列。
当遇到 matix[i][j] == 0时,将matix[0][j] 和 matrix[i][0] 置为 0。
第一遍遍历matrix结束后,将所记录的行和列置为0。
这样做需要注意:如果第一行或者第一列有0,需要额外记录。
代码:
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
if(matrix.size() == ) return;
if(matrix[].size() == ) return; bool firstRowSet = false;
bool firstColSet = false;
int i, j;
for(i = ; i < matrix.size(); ++i){
for(j = ; j < matrix[i].size(); ++j){
if(matrix[i][j] == ){
if(i == ) firstRowSet = true;
if(j == ) firstColSet = true;
matrix[i][] = ;
matrix[][j] = ;
}
}
} for(i = ; i < matrix.size(); ++i){
if(matrix[i][] == ){
for(j = ; j < matrix[i].size(); ++j)
matrix[i][j] = ;
}
} for(j = ; j < matrix[].size(); ++j){
if(matrix[][j] == ){
for(i = ; i < matrix.size(); ++i)
matrix[i][j] = ;
}
} if(firstRowSet)
for(j = ; j < matrix[].size(); ++j)
matrix[][j] = ;
if(firstColSet)
for(i = ; i < matrix.size(); ++i)
matrix[i][] = ;
}
};
[LeetCode] Matrix 值修改系列,例题 Surrounded Regions,Set Matrix Zeroes的更多相关文章
- [LeetCode] Surrounded Regions 包围区域
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured ...
- 验证LeetCode Surrounded Regions 包围区域的DFS方法
在LeetCode中的Surrounded Regions 包围区域这道题中,我们发现用DFS方法中的最后一个条件必须是j > 1,如下面的红色字体所示,如果写成j > 0的话无法通过OJ ...
- 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 用了第一种方式, ...
- 【LeetCode】130. Surrounded Regions (2 solutions)
Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A ...
- Leetcode之深度优先搜索(DFS)专题-130. 被围绕的区域(Surrounded Regions)
Leetcode之深度优先搜索(DFS)专题-130. 被围绕的区域(Surrounded Regions) 深度优先搜索的解题详细介绍,点击 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O) ...
- [LeetCode] 130. Surrounded Regions 包围区域
Given a 2D board containing 'X' and 'O'(the letter O), capture all regions surrounded by 'X'. A regi ...
- 【leetcode】Surrounded Regions
Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A ...
- LeetCode: Surrounded Regions 解题报告
Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A ...
- LeetCode解题报告—— Sum Root to Leaf Numbers & Surrounded Regions & Single Number II
1. Sum Root to Leaf Numbers Given a binary tree containing digits from 0-9 only, each root-to-leaf p ...
随机推荐
- 关于js中一个对象当做参数传递是按值传递还是按引用传递的个人看法
在<JavaScript高级程序设计>这本书中有这样一段话:有很多开发人员错误的认为:在局部作用域中修改的对象会在全局作用域中反映出来,就说明参数是按引用传递的.换句话说,尼古拉认为当一个 ...
- 0917 词法分析程序(java版)
1.运行结果: 2.源代码: package 词法分析;import java.util.Scanner;public class fenxi {public static void main(Str ...
- 使用C和C++实现“电梯”的区别
C 面向过程: 该电梯不允许未卜先知,故程序需逐条处理乘客请求并更新当前各变量状态. 如何获得最短时间:是否立即响应请求,计算出不同决策下的总时间,并进行比较,然后选择最短时间 ...
- 大白话Docker入门(一)
摘要: #大白话Docker入门(一) 随着docker现在越来越热门,自己也对docker的好奇心也越来越重,终于忍不住利用了一些时间把docker学习一遍.目前的资料不少,但是由于docker的发 ...
- .NET Core使用EF分页查询数据报错:OFFSET语法错误问题
在Asp.Net Core MVC项目中使用EF分页查询数据时遇到一个比较麻烦的问题,系统会报如下错误: 分页查询代码: ) * condition.PageSize).Take(condition. ...
- 在服务器中使用 Entity Framework 的 Migration 更新数据库
在开发环境中,每次我们对要对数据库进行更改,比如增加修改表字段等.改好Entity类后,我们只需在Nuget程序包管理控制台运行 update-database 脚本却可: update-databa ...
- .net MVC中使用angularJs刷新页面数据列表
使用angularjs的双向绑定功能,定时刷新页面上数据列表(不是刷新网页,通过ajax请求只刷新数据列表部分页面),实例如下: @{ Layout = null; } <!DOCTYPE ht ...
- 【bzoj5157】[Tjoi2014]上升子序列 树状数组
题目描述 求一个数列本质不同的至少含有两个元素的上升子序列数目模10^9+7的结果. 题解 树状数组 傻逼题,离散化后直接使用树状数组统计即可.由于要求本质不同,因此一个数要减去它前一次出现时的贡献( ...
- MSSQL数据库分页存储过程
create procedure [dbo].[p_splitpage] ), , , output, output as set nocount on declare @p1 int ,,@rowc ...
- 访问控制列表-细说ACL那些事儿(ACL应用篇)
1.ACL应用范围 通过前两期的ACL理论学习,大家知道ACL并不能单独完成控制网络访问行为或者限制网络流量的效果,而是需要应用到具体的业务模块才能实现上述功能. 那么ACL到底可以应用在哪些业务中呢 ...