class Solution { private int[][] dir= {{0,-1},{-1,0},{0,1},{1,0}}; private boolean[][] used; public boolean isMove(char[][] board,int x,int y) { if(x>=0&&x<board.length&&y>=0&&y<board[0].length) return true; return false; } public boolean dfs(char[][] board,int x,int y) { board[x][y]=‘*‘; //一旦发现为立即赋值 used[x][y]=true; //并设为已访问 for(int i=0;i<4;++i) { int newX=x+dir[i][0]; int newY=y+dir[i][1]; if(isMove(board,newX,newY)&&board[newX][newY]==‘o‘&&!used[newX][newY]&&dfs(board,newX,newY)) { return true; } } return false; } //并查集思想==找到一个点并把与它相关的点都标记起来再按这个标记做相应的处理 public void solve(char[][] board) { used=new boolean[board.length][board[0].length]; for(int i=0;i<board[0].length;++i) { if(board[0][i]==‘o‘) dfs(board,0,i); if(board[board.length-1][i]==‘o‘) dfs(board,board.length-1,i); } for(int i=0;i<board.length;++i) { if(board[i][0]==‘o‘) dfs(board,i,0); if(board[i][board[0].length-1]==‘o‘) dfs(board,i,board[0].length-1); } for(int i=0;i<board.length;++i) { for(int j=0;j<board[0].length;++j) { if(board[i][j]==‘*‘) board[i][j]=‘o‘; else if(board[i][j]==‘o‘) board[i][j]=‘x‘; } } for(int i=0;i<board.length;++i) { for(int j=0;j<board[0].length;++j) { System.out.print(board[i][j]); } System.out.println(); } } } public class Main { public static void main(String[] args) { Solution space=new Solution(); char[][]board= { {‘x‘,‘x‘,‘o‘,‘x‘,‘x‘}, {‘x‘,‘x‘,‘x‘,‘x‘,‘x‘}, {‘x‘,‘x‘,‘x‘,‘x‘,‘x‘}, {‘x‘,‘o‘,‘o‘,‘x‘,‘x‘}, {‘x‘,‘x‘,‘o‘,‘x‘,‘x‘}, {‘x‘,‘o‘,‘x‘,‘x‘,‘x‘} }; space.solve(board); } }
原文地址:https://www.cnblogs.com/z2529827226/p/11731487.html
时间: 2024-09-29 04:30:34