DFS+并查集思想求被围绕的区域
Posted z2529827226
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DFS+并查集思想求被围绕的区域相关的知识,希望对你有一定的参考价值。
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); } }
以上是关于DFS+并查集思想求被围绕的区域的主要内容,如果未能解决你的问题,请参考以下文章
CodeForces 731C Socks (DFS或并查集)