【图的dfs】—— 连通检测

本文深入探讨了使用深度优先搜索(DFS)算法进行图的连通性检测。通过Java实现,详细解释了如何遍历图的各个节点,确保所有节点都能被访问到,以此判断图是否连通。通过对图论概念的结合,揭示了DFS在解决图的连通性问题中的关键作用。

在这里插入图片描述在这里插入图片描述

import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();  
		sc.nextLine();
		char [][]graph = new char[n][n];
		for(int i=0;i<n;i++)
		    graph[i] = sc.nextLine().toCharArray();
		int m = sc.nextInt();
		int [][]query = new int[m][4];
		for(int i=0;i<m;i++){
			for(int j=0;j<4;j++){
				query[i][j] = sc.nextInt();
			}
		}
		for(int i=0;i<m;i++){
			boolean ok = check(graph,new int[n][n],query[i]);
			System.out.println(ok);
		}
	}
    
	//检查起点到终点是否连通,标记数组lable
	private static boolean check(char[][] graph, int[][] lable, int[] points) {
		int x1 = points[0];
		int y1 = points[1];
		int x2 = points[2];
		int y2 = points[3];
		
		if(x1 == x2 && y1 == y2)
			return true;
		
		int value = graph[x1][y1];
		boolean f1 = false;
		boolean f2 = false;
		boolean f3 = false;
		boolean f4 = false;
		//向左走
		//1.不能出界   2.左边位置没有被访问   3.左边与现在的是值一样 
		if(y1-1 >=0 && lable[x1][y1-1] == 0  && graph[x1][y1-1] == value ){
			lable[x1][y1-1] = 1;
			points[1] = y1-1;
			f1 = check(graph,lable,points);
			
			//回溯
			lable[x1][y1-1] = 0;
			points[1] = y1;
			
		}
		 
		if(y1+1 < graph.length && lable[x1][y1+1] == 0  && graph[x1][y1+1] == value){
			lable[x1][y1+1] = 1;
			points[1] = y1+1;
			f2 = check(graph,lable,points);
			
			//回溯
			lable[x1][y1+1] = 0;
			points[1] = y1;
		}

		if(x1+1 < graph.length && lable[x1+1][y1] == 0  && graph[x1+1][y1] == value ){
			lable[x1+1][y1] = 1;
			points[0] = x1+1;
			f3 = check(graph,lable,points);
			
			//回溯
			lable[x1+1][y1] = 0;
			points[0] = x1;
		}

		if(x1-1 >=0 && lable[x1-1][y1] == 0  && graph[x1-1][y1] == value ){
			lable[x1-1][y1] = 1;
			points[0] = x1-1;
			f4 = check(graph,lable,points);
			
			//回溯
			lable[x1-1][y1] = 0;
			points[0] = x1;
		}
		
		return f1 || f2 || f3 || f4;
	}	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值