LeetCode 题解(153): Surrounded Regions

2024-05-28 09:08

本文主要是介绍LeetCode 题解(153): Surrounded Regions,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

题目:

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

题解:

先用BFS把矩形最外面一圈遍历了,将由最外一圈‘O’所能访问到的全部‘O’标记为visited。然后遍历里面元素,遇见未访问过的'O'直接变为‘X’即可。

C++版:

class Solution {
public:void solve(vector<vector<char>>& board) {if(board.size() == 0)return;vector<vector<bool>> visited(board.size(), vector<bool>(board[0].size(), false));for(int j = 0; j < board[0].size(); j++) {visit(board, 0, j, visited);visit(board, board.size()-1, j, visited);}for(int i = 1; i < board.size() - 1; i++) {visit(board, i, 0, visited);visit(board, i, board[0].size()-1, visited);}for(int i = 1; i < board.size() - 1; i++) {for(int j = 1; j < board[0].size() - 1; j++) {if(!visited[i][j]) {visited[i][j] = true;if(board[i][j] == 'O')board[i][j] = 'X';}}}}void enclose(vector<vector<char>>& board, int i, int j, vector<vector<bool>>& visited) {visited[i][j] = true;if(board[i][j] == 'O') {queue<pair<int, int>> q;q.push(pair<int, int>(i, j));while(!q.empty()) {pair<int, int> current = q.front();q.pop();int x = current.first, y = current.second;addQ(board, q, x - 1, y, visited);addQ(board, q, x + 1, y, visited);addQ(board, q, x, y - 1, visited);addQ(board, q, x, y + 1, visited);}}}void addQ(vector<vector<char>>& board, queue<pair<int, int>>& q, int i, int j, vector<vector<bool>>& visited) {if(i < 0 || i >= board.size() || j < 0 || j >= board.size())return;if(board[i][j] == 'O') {if(!visited[i][j]) {visited[i][j] = true;q.push(pair<int, int>(i, j));}}}void visit(vector<vector<char>>& board, int i, int j, vector<vector<bool>>& visited) {if(visited[i][j])return;else {if(board[i][j] == 'O') {enclose(board, i, j, visited);} else {visited[i][j] = true;}}}
};

Java版:

class Position {int i;int j;Position(int x, int y) {i = x; j = y;}
}public class Solution {public void solve(char[][] board) {if(board.length == 0)return;int row = board.length, col = board[0].length;boolean[][] visited = new boolean[row][col];for(int j = 0; j < col; j++) {visit(board, 0, j, visited);visit(board, row-1, j, visited);}for(int i = 1; i < row - 1; i++) {visit(board, i, 0, visited);visit(board, i, col-1, visited);}for(int i = 1; i < row - 1; i++) {for(int j = 1; j < col - 1; j++) {if(!visited[i][j] && board[i][j] == 'O')board[i][j] = 'X';}}}public void visit(char[][] board, int i, int j, boolean[][] visited) {if(!visited[i][j] && board[i][j] == 'O') {enclose(board, i, j, visited);}}public void enclose(char[][] board, int i, int j, boolean[][] visited) {visited[i][j] = true;Queue<Position> q = new LinkedList<Position>();int row = board.length, col = board[0].length;q.add(new Position(i, j));while(q.size() != 0) {Position current = q.poll();int x = current.i, y = current.j;addQ(board, q, row, col, visited, x-1, y);addQ(board, q, row, col, visited, x+1, y);addQ(board, q, row, col, visited, x, y-1);addQ(board, q, row, col, visited, x, y+1);}}public void addQ(char[][] board, Queue<Position> q, int row, int col, boolean[][] visited, int i, int j) {if(i < 0 || j < 0 || i >= row || j >= col)return;if(!visited[i][j] && board[i][j] == 'O') {visited[i][j] = true;q.add(new Position(i, j));}}
}

Python版:

import Queueclass Solution:# @param {character[][]} board# @return {void} Do not return anything, modify board in-place instead.def solve(self, board):if len(board) == 0:returnvisited = [[False for i in range(len(board[0]))] for j in range(len(board))]for j in range(len(board[0])):self.visit(board, 0, j, visited)self.visit(board, len(board) - 1, j, visited)for i in range(1, len(board)-1):self.visit(board, i, 0, visited)self.visit(board, i, len(board[0])-1, visited)for i in range(1, len(board)-1):for j in range(1, len(board[0])-1):if not visited[i][j] and board[i][j] == 'O':board[i][j] = 'X'def visit(self, board, i, j, visited):if board[i][j] == 'O' and not visited[i][j]:self.enclose(board, i, j, visited)def enclose(self, board, i, j, visited):visited[i][j] = Trueq = Queue.Queue()q.put((i, j))while not q.empty():current = q.get()x, y = current[0], current[1]self.addQ(board, visited, x-1, y, q)self.addQ(board, visited, x+1, y, q)self.addQ(board, visited, x, y-1, q)self.addQ(board, visited, x, y+1, q)def addQ(self, board, visited, i, j, q):if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]):returnif board[i][j] == 'O' and not visited[i][j]:visited[i][j] = Trueq.put((i, j))


这篇关于LeetCode 题解(153): Surrounded Regions的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1010131

相关文章

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

【JavaScript】LeetCode:16-20

文章目录 16 无重复字符的最长字串17 找到字符串中所有字母异位词18 和为K的子数组19 滑动窗口最大值20 最小覆盖字串 16 无重复字符的最长字串 滑动窗口 + 哈希表这里用哈希集合Set()实现。左指针i,右指针j,从头遍历数组,若j指针指向的元素不在set中,则加入该元素,否则更新结果res,删除集合中i指针指向的元素,进入下一轮循环。 /*** @param

C - Word Ladder题解

C - Word Ladder 题解 解题思路: 先输入两个字符串S 和t 然后在S和T中寻找有多少个字符不同的个数(也就是需要变换多少次) 开始替换时: tips: 字符串下标以0开始 我们定义两个变量a和b,用于记录当前遍历到的字符 首先是判断:如果这时a已经==b了,那么就跳过,不用管; 如果a大于b的话:那么我们就让s中的第i项替换成b,接着就直接输出S就行了。 这样

LeetCode:64. 最大正方形 动态规划 时间复杂度O(nm)

64. 最大正方形 题目链接 题目描述 给定一个由 0 和 1 组成的二维矩阵,找出只包含 1 的最大正方形,并返回其面积。 示例1: 输入: 1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0输出: 4 示例2: 输入: 0 1 1 0 01 1 1 1 11 1 1 1 11 1 1 1 1输出: 9 解题思路 这道题的思路是使用动态规划

【秋招笔试】9.07米哈游秋招改编题-三语言题解

🍭 大家好这里是 春秋招笔试突围,一起备战大厂笔试 💻 ACM金牌团队🏅️ | 多次AK大厂笔试 | 大厂实习经历 ✨ 本系列打算持续跟新 春秋招笔试题 👏 感谢大家的订阅➕ 和 喜欢💗 和 手里的小花花🌸 ✨ 笔试合集传送们 -> 🧷春秋招笔试合集 🍒 本专栏已收集 100+ 套笔试题,笔试真题 会在第一时间跟新 🍄 题面描述等均已改编,如果和你笔试题看到的题面描述