Algorithms for gerrymandering over graphs