Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- namespace FloodFill
- {
- internal class Program
- {
- private const int MAP_SIZE = 1024; // only powers of two are supported
- private static void Main()
- {
- var map = new byte[MAP_SIZE * MAP_SIZE];
- var stopwatch = Stopwatch.StartNew();
- {
- FloodFill(map, startX: 123, startY: 123, fromValue: 0, toValue: 1);
- }
- stopwatch.Stop();
- Console.WriteLine(stopwatch.ElapsedMilliseconds);
- Console.ReadLine();
- }
- private static void FloodFill(byte[] map, int startX, int startY, byte fromValue, byte toValue)
- {
- int shift = (int) Math.Round(Math.Log(map.Length, 4)); // if the array's length is (2^x * 2^x), then size = x
- int startIndex = startX + (startY << shift);
- if (map[startIndex] != fromValue)
- {
- return;
- }
- int size = 1 << shift;
- int sizeMinusOne = size - 1;
- int xMask = size - 1;
- map[startIndex] = toValue;
- var queue = new Queue<int>();
- queue.Enqueue(startIndex);
- while (queue.Count > 0)
- {
- int index = queue.Dequeue();
- int x = index & xMask;
- int y = index >> shift;
- if (x > 0)
- {
- if (map[index - 1] == fromValue)
- {
- map[index - 1] = toValue;
- queue.Enqueue(index - 1);
- }
- }
- if (x < sizeMinusOne)
- {
- if (map[index + 1] == fromValue)
- {
- map[index + 1] = toValue;
- queue.Enqueue(index + 1);
- }
- }
- if (y > 0)
- {
- if (map[index - size] == fromValue)
- {
- map[index - size] = toValue;
- queue.Enqueue(index - size);
- }
- }
- if (y < sizeMinusOne)
- {
- if (map[index + size] == fromValue)
- {
- map[index + size] = toValue;
- queue.Enqueue(index + size);
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement