1.先来看题目
实现原理很简单,就是从边缘向内部搜索,你可以深度搜索或者广度搜索。就不做介绍了
/*
* @lc app=leetcode.cn id=130 lang=java
*
* [130] 被围绕的区域
*/
// @lc code=start
class Solution {
public void solve(char[][] board) {
bfs(board);
}
public static void bfs(char[][] data){
int h = data.length;
if (h == 0)
return;
int w = data[0].length;
Character[][] d2 = new Character[h][w];
int[][] flag = new int[h][w];
for (int i =0;i<h;i++){
for (int j =0;j<w;j++){
d2[i][j] = data[i][j];
flag[i][j] = 0;
}
}
Queue<IPoint> points = new LinkedList<>();
for (int i =0;i<h;i++){
for (int j =0;j<w;j++){
if (d2[i][j].toString() .equals("O") ){
if (i == 0||i == h-1||j == 0||j== w-1){
points.offer(new CPoint(i,j,d2));
}
}
}
}
//Debug.Log(points.size());
while (points.size()!= 0){
IPoint c1 = points.poll();
//.Log(c1.getValue().toString());
List<IPoint> nextList = c1.nextPoint(c1,d2);
flag[c1.getX()][c1.getY()] = 100;
//Debug.Log(c1.getX()+"<>"+c1.getY());
for (IPoint p : nextList){
if (p.isLegal(p.getX(),p.getY(),d2)){
if (p.getValue().toString().equals("O")){
if (flag[p.getX()][p.getY()] != 100){
points.offer(p);
}
}
}
}
}
String value = "";
for (int i =0;i<h;i++){
for (int j =0;j<w;j++){
if (flag[i][j] !=100){
data[i][j] = 'X';
}
value+= data[i][j];
}
value+= "\n";
}
//Debug.Log(value);
}
}
interface IPoint <T> {
boolean isLegal(int x,int y,T[][] arr);
List<IPoint> nextPoint(IPoint point,T[][] arr);
int getX();
int getY();
T getValue();
IPoint getParent();
IPoint setParent(IPoint parent);
IPoint getChild();
IPoint setChild(IPoint child);
}
class CPoint<T> implements IPoint<T> {
T value;
int x;
int y;
IPoint<T> child;
IPoint<T> parent;
public CPoint(int x,int y,T[][] arr){
this.x = x;
this.y = y;
this.value = arr[x][y];
}
@Override
public boolean isLegal(int x, int y, T[][] arr) {
int w = arr.length;
int h = arr[0].length;
if(x <= 0)
{
return false;
}
if(y<= 0){
return false;
}
if(x> w-1){
return false;
}
if(y > h-1){
return false;
}
return true;
}
@Override
public List<IPoint> nextPoint(IPoint point,T[][] arr) {
List<IPoint> pl = new ArrayList();
int[][] dir = new int[4][2];
dir[0] = new int[]{point.getX() - 1,point.getY()};
dir[1] = new int[]{point.getX()+ 1,point.getY()};
dir[2] = new int[]{point.getX(),point.getY() +1};
dir[3] = new int[]{point.getX(),point.getY() -1};
for (int i =0;i<4;i++){
if(isLegal(dir[i][0],dir[i][1],arr)){
CPoint c1 = new CPoint(dir[i][0],dir[i][1],arr);
c1.setParent(this);
pl.add(c1);
}
}
return pl;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public T getValue() {
return value;
}
@Override
public IPoint getParent() {
return parent;
}
@Override
public IPoint setParent(IPoint parent) {
this.parent = parent;
return parent;
}
@Override
public IPoint getChild() {
return child;
}
@Override
public IPoint setChild(IPoint child) {
this.child = child;
return parent;
}
}
// @lc code=end