Java – find the algorithm with the least number of transactions between people
I've been thinking about it
Suppose you have a list of books that people are selling I have a book. I want to buy a book in a Book (something I don't have)
In this case, everyone is selling a book with s and wants a book in a book
Is there an algorithm that can find the minimum number of transactions between people to get the book I want (and provide my book to the person I want)?
Please tell me if this is confusing (because it may be)
Thank you for answering this question!
Edit: the list can grow at any time
Solution
I'll turn it into a chart, as shown below Books are nodes of charts If someone in s offers Book B and wants book a, you have a targeted advantage from book a to book B You are looking for the shortest path from the book you have to the book you really want
The shortest path can be found by breadth first search You can do this as follows:
todo = [starting_book] path = {starting_book: None} while len(todo) and target_book not in path: book = list.pop(0) for next_book in neighbors(book): if next_book not in path: path[next_book] = book todo.append(next_book) if target_book in path: solution = [target_book] while solution[-1] != starting_book: solution.append(path[solution[-1]]) else: solution = None
Please note that the solution I provide here can realize a series of book transactions, not people The person who brings a particular book transaction back to the conversation can do so by searching s or looking up a table
This is also not an online solution - tracking the shortest path, because adding / removing things in s will be a lot of work