標籤:leetcode java 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 XX O O XX X O XX O X X
After running your function, the board should be:
X X X XX X X XX X X XX O X X
題意:
給定一個2維平麵包含‘X‘ 和 ‘O‘,填充所有的被‘X‘包圍的地區.
比如,
X X X XX O O XX X O XX O X X
運行完你的函數後,這個平面變為:
X X X XX O O XX X O XX O X X
演算法分析:
* 典型的BFS題目。遍曆每個字元,如果是“O”,則從當前字元開始BFS遍曆,如果周圍也是“O”則加入當前遍曆的隊列,
* 直到遍曆完所有相鄰的“O”,於此同時,判斷每個O是否是被包圍的,只要由一個O是沒有被包圍的,
* 則當前遍曆的O的集合都是沒有被包圍的,因為這些O都是相連的。
AC代碼:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution { public void solve(char[][] board) { if(board==null||board.length==0) return; int row=board.length; int col=board[0].length; boolean visited[][] = new boolean[row][col] ;//遍曆標記數組 for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { if(board[i][j]=='O'&&(!visited[i][j])) { bfs(board,i,j,visited);//若未遍曆過,則對該節點進行廣度優先搜尋 } } } }private void bfs(char[][] board,int i,int j,boolean visited[][]){ ArrayList<Integer> list =new ArrayList<Integer>(); Queue<Integer> queue = new LinkedList<Integer>();boolean label=true; int row=board.length; int col=board[0].length;int temjudge,temi,temj; queue.add(i*col+j);//將數組位置二維轉化為一維visited[i][j]=true;while(!queue.isEmpty()){ temjudge=queue.poll();list.add(temjudge);temj=temjudge%col;//列位置temi=(temjudge-temj)/col;//行位置if(temi==0||temj==0||temi==row-1||temj==col-1) label=false;//若該節點位於邊界處,這是沒有被圍,所以遍曆到的所有節點都不變化,這裡用label記錄一下if(temj>0&&board[temi][temj-1]=='O'&&!visited[temi][temj-1])//左{queue.add(temi*col+temj-1);visited[temi][temj-1]=true;}if(temi>0&&board[temi-1][temj]=='O'&&!visited[temi-1][temj])//上{queue.add((temi-1)*col+temj);visited[temi-1][temj]=true;}if(temj<board[0].length-1&&board[temi][temj+1]=='O'&&!visited[temi][temj+1])//右{queue.add(temi*col+temj+1);visited[temi][temj+1]=true;}if(temi<board.length-1&&board[temi+1][temj]=='O'&&!visited[temi+1][temj])//下{queue.add((temi+1)*col+temj);visited[temi+1][temj]=true;}}if(label)//遍曆到的所有的節點都沒有處於邊界,這是對這些節點進行變化{for(int k=0;k<list.size();k++){temjudge=list.get(k); temj=temjudge%col; temi=(temjudge-temj)/col;board[temi][temj]='X';}} }}</span>
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Surrounded Regions