Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static int answer(int[] entrances, int[] exits, int[][] path) {
- if(entrances.length == 0 || exits.length == 0)
- return 0;
- int[] max = new int[path.length]; // array for bunnies in each room
- // set max bunnies of entrances to how much they can send through their corridors
- for(int i = 0; i < entrances.length; i++) {
- for(int j = 0; j < path[entrances[i]].length; j++) {
- if(path[entrances[i]][j] != 0)
- max[entrances[i]] += path[entrances[i]][j];
- }
- }
- // calls recursive function to do the work
- for(int i = 0; i < entrances.length; i++)
- helper(entrances, exits, max, entrances[i], path);
- // takes all the bunnies in the exits and totals them
- int sum = 0;
- for(int i = 0; i < exits.length; i++)
- sum += max[exits[i]];
- return sum;
- }
- public static void helper(int[] ent, int[] exit, int[] max, int current, int[][] path) {
- if(checkIfExit(current, exit)) // if we reach an exit, return
- return;
- for(int i = 0; i < path.length; i++) {
- if(checkIfEnt(i, ent)) // Skip if hallway goes back to entrance
- continue;
- // send the bunnies through the corridors
- if(path[current][i] != 0 && max[current] != 0) { // If you have bunnies to send/there's a hallway
- if(max[current] >= path[current][i]) { // if more than enough bunnies in rooms, send how many can fit
- max[current] -= path[current][i];
- max[i] += path[current][i];
- path[current][i] = 0;
- helper(ent, exit, max, i, path);
- }
- else { // if not enough, send whatever you have
- max[i] += max[current];
- path[current][i] -= max[current];
- max[current] = 0;
- helper(ent, exit, max, i, path);
- }
- }
- }
- }
- public static boolean checkIfEnt(int floor, int[] ent) {
- for(int i = 0; i < ent.length; i++) {
- if(floor == ent[i])
- return true;
- }
- return false;
- }
- public static boolean checkIfExit(int floor, int[] exit) {
- for(int i = 0; i < exit.length; i++) {
- if(floor == exit[i])
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement