public static int step_simulation(ref c_octopus[][] octopi) { int flash_count = 0; Queue <c_octopus> flashed = new Queue <c_octopus>(); // First, the energy level of each octopus increases by 1. for (int row = 0; row < octopi.Length; row++) { for (int col = 0; col < octopi[row].Length; col++) { octopi[row][col].step(); if (octopi[row][col].flashed()) { flash_count++; flashed.Enqueue(octopi[row][col]); } } } // Then, any octopus with an energy level greater than 9 flashes. This // increases the energy level of all adjacent octopuses by 1, including // octopuses that are diagonally adjacent. If this causes an octopus to // have an energy level greater than 9, it also flashes.This process // continues as long as new octopuses keep having their energy level // increased beyond 9. (An octopus can only flash at most once per step.) while (flashed.Count > 0) { c_octopus octopus = flashed.Dequeue(); // This octopus flashed, so look at all neighbors foreach (c_octopus neighbor in get_neighbors(ref octopi, octopus)) { // If the neighbor hasn't flashed yet, boost them. if (!neighbor.flashed()) { neighbor.boost(); if (neighbor.flashed()) { flash_count++; flashed.Enqueue(neighbor); } } } } return(flash_count); }
public static List <c_octopus> get_neighbors(ref c_octopus[][] octopi, c_octopus octopus) { List <c_octopus> neighbors = new List <c_octopus>(); for (int neighbor_index = 0; neighbor_index < k_neighbor_offsets.GetLength(0); neighbor_index++) { int neighbor_row = octopus.row + k_neighbor_offsets[neighbor_index, 0]; int neighbor_col = octopus.col + k_neighbor_offsets[neighbor_index, 1]; if (neighbor_row >= 0 && neighbor_row < octopi.Length && neighbor_col >= 0 && neighbor_col < octopi[neighbor_row].Length) { neighbors.Add(octopi[neighbor_row][neighbor_col]); } } return(neighbors); }