1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | import java.util.LinkedList; import java.util.Scanner; public class Main { class Node { public Node (int numNode, Node node ){ this.numNode = numNode; this.before = node; } int numNode; Node before; } public static void main(String[] args) { Main n = new Main(); n.input(); n.hamingRoute(); n.display(); } Scanner sc = new Scanner(System.in); Node find = null; int n , k, startPoint, endPoint, qPointer = 0; int[] binary = new int[n]; boolean[] check; LinkedList<Node> q = new LinkedList<Node>(); public void input(){ n = sc.nextInt(); k = sc.nextInt(); binary = new int[n]; for(int i = 0 ; i < n ; i ++){ binary[i] = Integer.parseInt(sc.next(), 2); } startPoint = sc.nextInt()-1; endPoint = sc.nextInt()-1; q.offer(new Node(startPoint, null)); return; } public void hamingRoute(){ while (true) { check = new boolean[n]; Node targetNode = q.get(qPointer); Node temp = targetNode; while ((temp = temp.before) != null) check[temp.numNode] = true; check[targetNode.numNode] = true; for (int j = 0; j < n; j++) { if (check[j]) continue; if (getHamingDistance(binary[targetNode.numNode], binary[j])) { q.offer(new Node(j, targetNode)); if (j == endPoint) { find = new Node(j, targetNode); return; } } } qPointer++; } } public boolean getHamingDistance(int position, int target){ target = position ^ target; int count = 0; while(target > 0){ if(target%2 == 1) count++; target = target / 2; } return (count == 1) ? true : false; } public void display(){ LinkedList<Integer> flow = new LinkedList<Integer>(); do{ flow.push(find.numNode+1); }while((find = find.before) != null); while(flow.size() > 0) System.out.print(flow.pop() + " "); return; } } | cs |
BFS 문제 풀이중입니다.
'알고리즘 > BFS' 카테고리의 다른 글
[ BFS / 정올 ] 1082 : 화염에서탈출 (0) | 2016.04.23 |
---|