給你一個m x n
的矩陣board
,由若干字符'X'
和'O'
,找到所有被'X'
圍繞的區(qū)域,并將這些區(qū)域里所有的?'O'
用'X'
填充。
示例 1:
輸入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] 輸出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] 解釋:被圍繞的區(qū)間不會存在于邊界上,換句話說,任何邊界上的?'O'
都不會被填充為?'X'
。 任何不在邊界上,或不與邊界上的?'O'
相連的?'O'
最終都會被填充為?'X'
。如果兩個元素在水平或垂直方向相鄰,則稱它們是“相連”的。
示例 2:
輸入:board = [["X"]] 輸出:[["X"]]提示:
m == board.length
n == board[i].length
1<= m, n<= 200
board[i][j]
為'X'
或'O'
class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0) return;
int m = board.length;
int n = board[0].length;
for (int i = 0; i< m; i++) {
for (int j = 0; j< n; j++) {
// 從邊緣o開始搜索
boolean isEdge = i == 0 || j == 0 || i == m - 1 || j == n - 1;
if (isEdge && board[i][j] == 'O') {
dfs(board, i, j);
}
}
}
for (int i = 0; i< m; i++) {
for (int j = 0; j< n; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
}
if (board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
}
public void dfs(char[][] board, int i, int j) {
if (i< 0 || j< 0 || i >= board.length || j >= board[0].length || board[i][j] == 'X' || board[i][j] == '#') {
// board[i][j] == '#' 說明已經(jīng)搜索過了.
return;
}
board[i][j] = '#';
dfs(board, i - 1, j); // 上
dfs(board, i + 1, j); // 下
dfs(board, i, j - 1); // 左
dfs(board, i, j + 1); // 右
}
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
當(dāng)前標(biāo)題:leetcode130.被圍繞的區(qū)域-創(chuàng)新互聯(lián)
當(dāng)前URL:http://aaarwkj.com/article20/dpgoco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、App開發(fā)、企業(yè)網(wǎng)站制作、搜索引擎優(yōu)化、網(wǎng)站營銷、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容