牛牛想知道,他是否能从 号格子出发回到 号格子。
若能回到 号格子则返回Yes,否则返回No。
若能回到 号格子则返回Yes,否则返回No。
[4, 4],[(1,2), (2, 3), (3,4),(4,1)]
"Yes"
m对 u, v 互不相同
import java.util.*; public class Solution { public int n; public int m; public String solve (int[] param, Point[] edge) { if(param.length != 2){ return "No"; } n = param[0]; //节点 m = param[1]; //边 if(edge.length != m || edge.length == 0){ return "No"; } boolean res = false; for(int i = 0; i < m; i++){ if(edge[i].x == 1){ if(edge[i].y == 1){ return "Yes"; } res = dfs(edge, 1, new boolean[m]); if(res){ return "Yes"; } } } return "No"; } public Boolean dfs(Point[] edge, int node, boolean[] visited){ boolean res = false; for(int j = 0; j < m; j++){ if(!visited[j]){ if(edge[j].x == node){ if(edge[j].y == 1){ return true; }else{ visited[j] = true; res = dfs(edge, edge[j].y, visited); visited[j] = false; if(res){ return true; } } } if(edge[j].y == node){ if(edge[j].x == 1){ return true; }else{ visited[j] = true; res = dfs(edge, edge[j].x, visited); visited[j] = false; if(res){ return true; } } } } } return false; } }
/** * 能回到1号点返回 Yes,否则返回 No * * @param param int整型一维数组 param[0] 为 n,param[1] 为 m * @param edge Point类一维数组 Point.x , Point.y 分别为一条边的两个点 * @return string字符串 */ boolean[] marked; int m; Point[] edge; public String solve(int[] param, Point[] edge) { // write code here m = edge.length; if (param[1] >= 100000) return "No"; marked = new boolean[m]; this.edge = edge; for (int i = 0; i < m; i++) { if (edge[i].x == 1 || edge[i].y == 1) { if (dfs(edge[i], 1, i, 1)) return "Yes"; } } return "No"; } /** * 判断是否有回路 * @param point 当前传入的点 * @param len 最大长度 * @param index 当前点的索引坐标 * @param p 上个节点的传入值 * @return 是否有回路 */ public boolean dfs(Point point, int len, int index, int p) { if (len == m) return point.y == 1 || point.x == 1; if (len > 1 && ((point.x == 1) || (point.y) == 1)) return true; marked[index] = true; for (int i = 0; i < m; i++) { if ((edge[i].x == p || p == edge[i].y) && !marked[i]) { if (edge[i].x == p) { if (dfs(edge[i], len + 1, i, edge[i].y)) return true; } if (edge[i].y == p) { if (dfs(edge[i], len + 1, i, edge[i].x)) return true; } } } marked[index] = false; return false; }