The Program Works for arrays upto 20x20 But for anything larger it throws an OutOfMemoryException.
Below is the code:
public static Point GetFinalPath(int x, int y) {
queue.Enqueue(new Point(x,y, null));
while(queue.Count>0) {
Point p = queue.Dequeue();
if (arr[p.x,p.y] == 9) {
Console.WriteLine("Found Destination");
return p;
}
if(IsOpen(p.x+1,p.y)) {
arr[p.x,p.y] = 1;
queue.Enqueue(new Point(p.x+1,p.y, p));
}
//similarly for the other directions
}
return null;
}
public int[,] SolutionMaze()
{
Point p = GetFinalPath(0, 0);
while (p.getParent() != null)
{
solvedarray[p.x, p.y] = 9;
p = p.getParent();
}
return solvedarray;
}
ok people here is the rest of the code
public static Queue<Point> queue=new Queue<Point>();
public static bool IsOpen(int x, int y)
{
//BOUND CHECKING
if ((x >= 0 && x < XMAX) && (y >= 0 && y < YMAX) && (arr[x,y] == 0 || arr[x,y] == 9))
{
return true;
}
return false;
}
public class Point
{
public int x;
public int y;
Point parent;
public Point(int x, int y, Point parent)
{
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent()
{
return this.parent;
}
}
Assumes start to be 0,0 and final destination is set as 9 at the constructor.
Help me implement this for an array of size 500x500
Well, looking at your code I found one problem. You perform the wrong check. You should check if your point is already added to a queue. What do you do now? We'll, you are just marking processed cell as not open. It's easy to see that you can add to queue same node twice.
Let's follow my example:
1 | . .
0 | ! .
--+----
yx| 0 1
Queue: point (0,0)
We are starting at point(0,0). At this moment, we are adding points (0, 1) and (1,0) to our queue and mark point(0,0) as processed
1 | . .
0 | X !
--+----
yx| 0 1
Queue: point (0,1), point (1,0)
Now we dequeue point(0,1), marking it processed and adding point(1,1) to queue.
1 | ! .
0 | X X
--+----
yx| 0 1
Queue: point (1,0), point(1,1)
Now we dequeue point(1,0), marking it as processed and adding point(1,1) to queue:
1 | X !
0 | X X
--+----
yx| 0 1
Queue: point (1,1), point (1,1)
And now we have same point twice in a queue. And that is not your last problem. Your points have a reference to all it parents, so your previous points (doubled too) can't be processed with Garbage Collector.
Okay i found an answer to the OutOfMemory. Now the code works even for 500x500 matrix
As it turns out i just implemented a node list which keeps track of added nodes in queue using y*MAX_X_LENGTH + x formula
public static Queue<Point> queue=new Queue<Point>();
public SolveMaze(int[,] array,int staX,int staY,int finX,int finY)
{
//sets Destination as 9
arr = array;
XMAX = array.GetLength(0);
YMAX = array.GetLength(1);
finishY = finX; finishX = finY; startY = staX; startX = staY;
solvedarray = new int[XMAX, YMAX];
}
public static List<int> nodelist=new List<int>();
public void AddPointToQueueIfOpenAndNotAlreadyPresent(Point p,int direction)
{
if (nodelist.Contains(XMAX * p.y + p.x))
return;
else
{
switch(direction){
case 1:
//north
if (IsOpen(p.x, p.y - 1))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x, p.y - 1, p));
nodelist.Add(XMAX * (p.y - 1) + p.x);
}
break;
case 0:
//east
if (IsOpen(p.x + 1, p.y))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x + 1, p.y, p));
nodelist.Add(XMAX * (p.y) + p.x + 1);
}
break;
case 3:
//south
if (IsOpen(p.x, p.y + 1))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x, p.y +1, p));
nodelist.Add(XMAX * (p.y + 1) + p.x);
}
break;
case 2:
//west
if (IsOpen(p.x - 1, p.y))
{
arr[p.x, p.y] = 1;
queue.Enqueue(new Point(p.x - 1, p.y, p));
nodelist.Add(XMAX * (p.y) + p.x-1);
}
break; }
}
}
public Point GetFinalPath(int x, int y) {
if (arr[finishX, finishY] == 0)
arr[finishX, finishY] = 9;
else
return null;
queue.Enqueue(new Point(x, y, null));
nodelist.Add(XMAX * y + x);
while(queue.Count>0) {
Point p = queue.Dequeue();
nodelist.Remove(p.y * XMAX + p.x);
if (arr[p.x,p.y] == 9) {
Console.WriteLine("Exit is reached!");
return p;
}
for (int i = 0; i < 4; i++)
{
AddPointToQueueIfOpenAndNotAlreadyPresent(p, i);
}
}
return null;
}
public static bool IsOpen(int x, int y)
{
//BOUND CHECKING
if ((x >= 0 && x < XMAX) && (y >= 0 && y < YMAX) && (arr[x,y] == 0 || arr[x,y] == 9))
{
return true;
}
return false;
}
public int[,] SolutionMaze()
{
Point p = GetFinalPath(startX, startY);
if(p!=null)
while (p.getParent() != null)
{
solvedarray[p.x, p.y] = 9;
p = p.getParent();
}
return solvedarray;
}
}
public class Point
{
public int x;
public int y;
Point parent;
public Point(int x, int y, Point parent)
{
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent()
{
return this.parent;
}
}
Related
I've been working on a project which needs the knight(we have it's coordinates at the start) travel to destination(also known coordinates).
I tried to write using recursion but my code doesn't seem to be doing anything and I can't find the problem. Here's my code:
static bool Kelias(int dabX, int dabY, string[] Lenta, int dX, int dY, int indeksas)
{
if (dabX == dX && dabY == dY)
return true;
if (!Lenta[dabY][dabX].Equals('0'))
{
return false;
}
if (indeksas > 0)
{
StringBuilder naujas = new StringBuilder(Lenta[dabY]);
naujas[dabX] = (char)indeksas;
Lenta[dabY] = naujas.ToString();
}
// aukstyn desinen
if (GaliJudeti(dabX + 2, dabY + 1)
&& Kelias(dabX + 2, dabY + 1, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// aukstyn desinen
if (GaliJudeti(dabX + 1, dabY + 2)
&& Kelias(dabX + 1, dabY + 2, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// aukstyn kairen
if (GaliJudeti(dabX - 1, dabY + 2)
&& Kelias(dabX - 1, dabY + 2, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// aukstyn kairen
if (GaliJudeti(dabX - 2, dabY + 1)
&& Kelias(dabX - 2, dabY + 1, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// zemyn kairen
if (GaliJudeti(dabX - 2, dabY - 1)
&& Kelias(dabX - 2, dabY - 1, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// zemyn kairen
if (GaliJudeti(dabX - 1, dabY - 2)
&& Kelias(dabX - 1, dabY - 2, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// zemyn desinen
if (GaliJudeti(dabX + 1, dabY - 2)
&& Kelias(dabX + 1, dabY - 2, Lenta, dX, dY, indeksas + 1))
{
return true;
}
// zemyn desinen
if (GaliJudeti(dabX + 2, dabY - 1)
&& Kelias(dabX + 2, dabY - 1, Lenta, dX, dY, indeksas + 1))
{
return true;
}
indeksas--;
return false;
}
static bool GaliJudeti(int x, int y)
{
if (x >= 0 && y >= 0 && x < 8 && y < 8)
{
return true;
}
return false;
}
A little explanation about the variables and what I'm trying to do:
dabX, dabY - are the current coordinates of the Knight
Lenta - is my board(it's a string cause I'm reading the starting data from a txt file).
dX, dY - is the target destination
indeksas - is a tracker of how many moves it takes to reach the destination
Now the first if checks if we reached the destination. Second one checks if the coordinates to which we're traveling too are not obstructed(Since my board is made out of zeroes cause it's in a string we check if the symbol is equal to it cause if it's not means path is obstructed). Then we move onto the knights possible movements which is the main part of the method.
Also there's another function called GaliJudeti which checks if we're in bounds of the board(8x8).
Your code looks like it must work. I just used your algorithm, modified it a bit and everything works fine. I used classes to make it look more generally, but in fact it's all the same.
static bool MoveFirstSolution(Knight knight, Board board, Point destination, int counter, Trace trace)
{
board.Set(knight.X, knight.Y, counter);
if (knight.IsInPoint(destination))
{
//trace is an object to store found path
trace.Counter = counter;
trace.Board = board;
return true;
}
counter++;
Point[] moves = knight.AllPossibleMoves();
foreach (Point point in moves)
{
if (board.Contains(point) && board.IsFree(point))
{
knight.MoveTo(point);
if (MoveFirstSolution(knight, board.GetCopy(), destination, counter, trace))
{
return true;
}
}
}
return false;
}
However, this function will find first solution and stop. If you want best solution, you need to continue the search even when the answer is found. Here is a function to perform it:
static void Move(Knight knight, Board board, Point destination, int counter, Trace trace)
{
board.Set(knight.X, knight.Y, counter);
if (knight.IsInPoint(destination))
{
if (!trace.IsShorterThen(counter))
{
trace.Counter = counter;
trace.Board = board;
Console.WriteLine("Better trace");
Console.WriteLine("Counter: " + trace.Counter);
Console.WriteLine(trace.Board);
}
return;
}
counter++;
Point[] moves = knight.AllPossibleMoves();
foreach(Point point in moves)
{
if (board.Contains(point) && board.IsFree(point))
{
knight.MoveTo(point);
Move(knight, board.GetCopy(), destination, counter, trace);
}
}
}
The trace is overwritten each time when better one is found. But for 8 * 8 board it takes really long time to execute.
For your code I can advise to try Console.WriteLine() to be sure, that everything works. Maybe, you Lenta is not overwritten, as you expected and this causes infinite recursion. Try tracking each action of your function, to find the source of problem.
Here are my main function:
static void Main(string[] args)
{
Knight knight = new Knight(0, 0);
Board board = new Board(8, 8);
Point destination = new Point(0, 4);
Trace bestTrace = new Trace();
MoveFirstSolution(knight, board, destination, 1, bestTrace);
Console.WriteLine("Best trace: " + bestTrace.Counter);
Console.WriteLine(bestTrace.Board);
Console.ReadLine();
}
and the rest of required classes, so you can try it as working example.
class Trace
{
public Trace()
{
this.Board = null;
this.Counter = -1;
}
public Trace(Board board, int counter)
{
this.Board = board;
this.Counter = counter;
}
public bool IsShorterThen(int counter)
{
return this.Counter > 0 && this.Counter <= counter;
}
public Board Board { get; set; }
public int Counter { get; set; }
}
class Board
{
private int[][] _board;
public Board(int N, int M)
{
this._board = new int[N][];
for (int i = 0; i < N; i++)
{
this._board[i] = new int[M];
for (int j = 0; j < M; j++)
{
this._board[i][j] = 0;
}
}
}
public int N
{
get
{
return this._board.Length;
}
}
public int M
{
get
{
return this._board.Length > 0 ? this._board[0].Length : 0;
}
}
public Board GetEmptyCopy()
{
return new Board(this.N, this.M);
}
public Board GetCopy()
{
Board b = new Board(this.N, this.M);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
b.Set(i, j, this.Get(i, j));
}
}
return b;
}
public bool Contains(int i, int j)
{
return (i >= 0) && (i < this.N) && (j >= 0) && (j < this.M);
}
public bool Contains(Point point)
{
return this.Contains(point.X, point.Y);
}
public bool IsFree(int i, int j)
{
return this._board[i][j] == 0;
}
public bool IsFree(Point point)
{
return this.IsFree(point.X, point.Y);
}
public void Set(int i, int j, int val)
{
this._board[i][j] = val;
}
public int Get(int i, int j)
{
return this._board[i][j];
}
public override string ToString()
{
string str = "";
for (int i = 0; i < this.N; i++)
{
for (int j = 0; j < this.M; j++)
{
str += String.Format("{0, 3}", this._board[i][j]);
}
str += "\r\n";
}
return str;
}
}
class Knight
{
public Knight(int x, int y)
{
this.X = x;
this.Y = y;
}
public int X { get; private set; }
public int Y { get; private set; }
public Point[] AllPossibleMoves()
{
Point[] moves = new Point[8];
moves[0] = new Point(this.X + 1, this.Y + 2);
moves[1] = new Point(this.X + 1, this.Y - 2);
moves[2] = new Point(this.X + 2, this.Y + 1);
moves[3] = new Point(this.X + 2, this.Y - 1);
moves[4] = new Point(this.X - 1, this.Y + 2);
moves[5] = new Point(this.X - 1, this.Y - 2);
moves[6] = new Point(this.X - 2, this.Y + 1);
moves[7] = new Point(this.X - 2, this.Y - 1);
return moves;
}
public bool IsInPoint(int x, int y)
{
return this.X == x && this.Y == y;
}
public bool IsInPoint(Point point)
{
return this.IsInPoint(point.X, point.Y);
}
public void MoveTo(int x, int y)
{
this.X = x;
this.Y = y;
}
public void MoveTo(Point point)
{
this.MoveTo(point.X, point.Y);
}
}
class Point
{
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public int X { get; private set; }
public int Y { get; private set; }
}
I am trying to implement the algorithm described in the following http://repositorium.sdum.uminho.pt/bitstream/1822/6429/1/ConcaveHull_ACM_MYS.pdf
I am using the following class libraries. Loyc libs come from http://core.loyc.net/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Device.Location;
using Loyc.Collections;
using Loyc.Geometry;
using Loyc;
Here is the basic class
public class Hulls
{
private static List<Point<double>> KNearestNeighbors(List<Point<double>> points, Point<double> currentPoint, int k, out int kk)
{
kk = Math.Min(k, points.Count - 1);
var ret = points
.OrderBy(x => PointMath.Length(new Vector<double>(currentPoint.X - x.X, currentPoint.Y - x.Y)))
.Take(k)
.ToList();
return ret;
}
private static double Angle(Point<double> a, Point<double> b)
{
var ret = -Math.Atan2(b.Y - a.Y, b.X - a.X);
return NormaliseAngle(ret);
}
private static double NormaliseAngle(double a)
{
//while (a < b - Math.PI) a += Math.PI * 2;
//while (b < a - Math.PI) b += Math.PI * 2;
if (a < 0.0) { return a + Math.PI + Math.PI; }
return a;
}
private static List<Point<double>> SortByAngle(List<Point<double>> kNearest, Point<double> currentPoint, double angle)
{
//kNearest
// .Sort((v1, v2) => AngleDifference(angle, Angle(currentPoint, v1)).CompareTo(AngleDifference(angle, Angle(currentPoint, v2))));
//return kNearest.ToList();
kNearest = kNearest.OrderByDescending(x => NormaliseAngle(Angle(currentPoint, x) - angle)).ToList();
return kNearest;
}
private static bool CCW(Point<double> p1, Point<double> p2, Point<double> p3)
{
var cw = ((p3.Y - p1.Y) * (p2.X - p1.X)) - ((p2.Y - p1.Y) * (p3.X - p1.X));
return cw > 0 ? true : cw < 0 ? false : true; // colinear
}
private static bool _Intersect(LineSegment<double> seg1, LineSegment<double> seg2)
{
return CCW(seg1.A, seg2.A, seg2.B) != CCW(seg1.B, seg2.A, seg2.B) && CCW(seg1.A, seg1.B, seg2.A) != CCW(seg1.A, seg1.B, seg2.B);
}
private static bool Intersect(LineSegment<double> seg1, LineSegment<double> seg2)
{
if ((seg1.A.X == seg2.A.X && seg1.A.Y == seg2.A.Y)
|| (seg1.B.X == seg2.B.X && seg1.B.Y == seg2.B.Y))
{
return false;
}
if (_Intersect(seg1, seg2))
{
return true;
}
return false;
}
public IListSource<Point<double>> KNearestConcaveHull(List<Point<double>> points, int k)
{
points.Sort((a, b) => a.Y == b.Y ? (a.X > b.X ? 1 : -1) : (a.Y >= b.Y ? 1 : -1));
Console.WriteLine("Starting with size {0}", k.ToString());
DList<Point<double>> hull = new DList<Point<double>>();
var len = points.Count;
if (len < 3) { return null; }
if (len == 3) { return hull; }
var kk = Math.Min(Math.Max(k, 3), len);
var dataset = new List<Point<double>>();
dataset.AddRange(points.Distinct());
var firstPoint = dataset[0];
hull.PushFirst(firstPoint);
var currentPoint = firstPoint;
dataset.RemoveAt(0);
double previousAngle = 0;
int step = 2;
int i;
while ((currentPoint != firstPoint || step == 2) && dataset.Count > 0)
{
if (step == 5) { dataset.Add(firstPoint); }
var kNearest = KNearestNeighbors(dataset, currentPoint, k, out kk);
var cPoints = SortByAngle(kNearest, currentPoint, previousAngle);
var its = true;
i = 0;
while (its == true && i < cPoints.Count)
{
i++;
int lastPoint = 0;
if (cPoints[i - 1] == firstPoint)
{
lastPoint = 1;
}
int j = 2;
its = false;
while (its == false && j < hull.Count - lastPoint)
{
LineSegment<double> line1 = new LineSegment<double>(hull[step - 2], cPoints[i - 1]);
LineSegment<double> line2 = new LineSegment<double>(hull[step - 2 - j], hull[step - 1 - j]);
//its = LineMath.ComputeIntersection(line1, line2, out pfrac, LineType.Segment);
its = Intersect(line1, line2);
j++;
}
}
if (its == true)
{
return KNearestConcaveHull(points, kk + 1);
}
currentPoint = cPoints[i - 1];
hull.PushLast(currentPoint);
previousAngle = Angle(hull[step - 1], hull[step - 2]);
dataset.Remove(currentPoint);
step++;
}
bool allInside = true;
i = dataset.Count;
while (allInside == true && i > 0)
{
allInside = PolygonMath.IsPointInPolygon(hull, dataset[i - 1]);
i--;
}
if (allInside == false) { return KNearestConcaveHull(points, kk + 1); }
return hull;
}
}
The above is supposed to pick a new edge for the boundary based on the furthest right-hand turn from the previous edge going around the point set counterclockwise. The code seems to pick the correct first edge from the initial vertex which has the lowest y-value, but then does not pick the next edge correctly when the offset angle is nonzero. I think the issue is the SortByAngle or Angle. -atan2 would return the clockwise turn, correct? Possibly I should be adding the offset angle?
EDIT (SOLUTION): Found the issue after following Eric's helpful advice provided in the first comment to the question. It was SortByAngle and Angle:
private static double Angle(Point<double> a, Point<double> b)
{
var ret = Math.Atan2(b.Y - a.Y, b.X - a.X);
return NormaliseAngle(ret);
}
private static double NormaliseAngle(double a)
{
if (a < 0.0) { return a + Math.PI + Math.PI; }
return a;
}
private static List<Point<double>> SortByAngle(List<Point<double>> kNearest, Point<double> currentPoint, double angle)
{
//kNearest = kNearest.OrderByDescending(x => NormaliseAngle(Angle(currentPoint, x) - angle)).ToList();
kNearest.Sort((a, b) => NormaliseAngle(Angle(currentPoint, a) - angle) > NormaliseAngle(Angle(currentPoint, b) - angle) ? 1 : -1);
return kNearest;
}
You have some bug:
var kNearest = KNearestNeighbors(dataset, currentPoint, k, out kk);
Change the kk to just some var. You override the incrementation of that "kk" value, and then you're getting StackOverflow exceptions.
Change your code to the following:
int someVal;
var kNearest = KNearestNeighbors(dataset, currentPoint, k, out someVal);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hallo I can see this question been asked before. However I do not understand or can see how I can implment it myself. If its possible could you explain what you are doing and maybe add some kind of pseudo code so I can see the flow of the script.
I've done the vertical and horizontal lines like this and yes PlayingBoard is a 2d Array:
private void HasWon(int xPlaced, int yPlaced) {
//MessageBox.Show(xPlaced.ToString()+","+yPlaced.ToString());
int[] Coords = new int[2];
/// <summary>
/// This part checks if we have a win on East or West
/// </summary>
Coords[0] = xPlaced;
Coords[1] = yPlaced;
while(Coords[0] != 0)
{
Coords[0] -= 1;
if (PlayingBoard[Coords[0], Coords[1]] == playerValue)
{
foundInRow += 1;
}
else { break; }
}
Coords[0] = xPlaced;
Coords[1] = yPlaced;
while (Coords[0] < 6)
{
Coords[0] += 1;
if (PlayingBoard[Coords[0], Coords[1]] == playerValue)
{
foundInRow += 1;
}
else { break; }
}
if (foundInRow > 2) { MessageBox.Show("You won."); Won = true; }
else { foundInRow = 0; Won = false; }
/// <summary>
/// This part checks if we have a win on North or South
/// </summary>
Coords[0] = xPlaced;
Coords[1] = yPlaced;
while(Coords[1] != 0)
{
Coords[1] -= 1;
if (PlayingBoard[Coords[0], Coords[1]] == playerValue)
{
foundInRow += 1;
}
else { break; }
}
Coords[0] = xPlaced;
Coords[1] = yPlaced;
while (Coords[1] < 6)
{
Coords[1] += 1;
if (PlayingBoard[Coords[0], Coords[1]] == playerValue)
{
foundInRow += 1;
}
else { break; }
}
if (foundInRow > 2) { MessageBox.Show("You won."); Won = true; }
else { foundInRow = 0; Won = false; }
}
Here is a connect four solver which works using recursion.
It accepts a 2 dimensional array b which represents the board. each element in the array can be populated with an int where 0 represents an empty space 1 player one, 2 player two etc
the Checkboard method returns an int where -1 represents no winner and positive integers represent the winning players number
the method works by iterating through each square in the array from 0,0 and checking the three possible directions, left, diagonal and down for a further 3 adjacent elements containing the same number. if a row of 4 is found the method returns the number in the square it was checking at the time.
public class Connect4Solver
{
public int Checkboard(int[,] b)
{
for (int x = 0; x < b.GetLength(0); x++)
{
for (int y = 0; y < b.GetLength(1); y++)
{
for (int d = 0; d < 3; d++)
{
int p = b[x, y];
if (p != 0)
{
if (countDir(0, b, x, y, d, p) >= 3)
{
//win for p
return p;
}
}
}
}
}
return -1;
}
protected int countDir(int depth, int[,] b, int x, int y, int dir, int p)
{
int x2;
int y2;
if (getposdir(b, x, y, dir, out x2, out y2) == p)
{
//good
depth++;
return countDir(depth, b, x2, y2, dir, p);
}
else
{
return depth;
}
}
protected int getposdir(int[,] b, int x, int y, int dir, out int x2, out int y2)
{
if (dir == 0)
{
x2 = x + 1;
y2 = y;
}
else if (dir == 1)
{
x2 = x + 1;
y2 = y + 1;
}
else if (dir == 2)
{
x2 = x;
y2 = y + 1;
}
else
{
throw new Exception("unknown");
}
return getpos(b, x2, y2);
}
protected int getpos(int[,] b, int x, int y)
{
if (b.GetLength(0) <= x)
{
return -1;
}
if (b.GetLength(1) <= y)
{
return -1;
}
return b[x, y];
}
}
note: I forgot to check 'down and right' assuming it would like 'down'
and 'left' not be required. I leave this as an exercise for the reader
to add
Creating a Go Board Game but I'm stuck at checking the board for groups of stones that have been surrounded. To do this I thought I'd need to come up with some recursive functionality:
(Updated)
public List<Point> FindSurrounded(Board board, Point p, Player player, List<Point> group)
{
int[,] b = board.board;
for (int dx = -1; dx <= 1; dx++){
for (int dy = -1; dy <= 1; dy++)
{
//check if group allready contain this spot
if (p.X + dx < board.width && p.Y + dy < board.height && p.X + dx > 0 && p.Y + dy > 0 && (dy == 0 || dx == 0) && !(dy == 0 && dx == 0) && !group.Contains(new Point(p.X + dx, p.Y + dy)))
{
// is the spot empty
if (b[p.X + dx, p.Y + dy] == 0)
return null;
//check the suroundings of this spot and add them to the group
//if(b[p.X + dx, p.Y + dy] != player.Identifier)// is there an enemy on this spot
// return new List<Point>();
if (b[p.X + dx, p.Y + dy] != player.Identifier)
{
group.Add(new Point(p.X + dx, p.Y + dy));
List<Point> temp = FindSurrounded(board, new Point(p.X + dx, p.Y + dy), player, new List<Point>());
if (temp == null)
return null;
//group.AddRange(temp);
}
}
}
}
return group;
}
This code however gives me a System.StackOverFlowException error when I put a stone that surrounds stones of the opponent. The error would concern the following line:
if (p.X + dx < board.width && p.Y + dy < board.height && p.X + dx > 0 && p.Y + dy > 0 && (dy == 0 || dx == 0) && !(dy == 0 && dx == 0) && !group.Contains(new Point(p.X + dx, p.Y + dy)))
But I have no idea why.
Does anyone know a way in which I can check whether a group of stones on the board is surrounded?
Thanks in advance!
Best regards,
Skyfe.
EDIT: Forgot to mention I still have to create an array to temporarily store all found stones that form a group together in order to remove them from the board when they're surrounded.
Answer to the specific question:
Does anyone know a way in which I can check whether a group of stones on the board is surrounded?
Try this approach:
Board b;
int N, M; // dimensions
int timer;
int[,] mark; // assign each group of stones a different number
int[,] mov = // constant to look around
{
{ 0, -1 }, { 0, +1 },
{ -1, 0 }, { +1, 0 }
};
// Checks for a group of stones surrounded by enemy stones
// Returns the first group found or null if there is no such group.
public List<Point> CheckForSurrounded()
{
mark = new int[N,M];
for (int i = 0; i < b.SizeX; ++i)
for (int j = 0; j < b.SizeX; ++j)
if (mark[i, j] == 0) // not visited
{
var l = Fill(i, j);
if (l != null)
return l;
}
return null;
}
// Marks all neighboring stones of the same player in cell [x,y]
// Returns the list of stones if they are surrounded
private List<Point> Fill(int x, int y)
{
int head = 0;
int tail = 0;
var L = new List<Point>();
mark[x, y] = ++timer;
L.Add(new Point(x,y));
while (head < tail)
{
x = L[head].X;
y = L[head].Y;
++head;
for (int k = 0; k < 4; ++k)
{
// new coords
int xx = x + mov[k,0];
int yy = y + mov[k,1];
if (xx >= 0 && xx < N && yy >= 0 && yy < M) // inside board
{
if (mark[xx, yy] == 0) // not visited
{
if (b[xx, yy].IsEmpty) // if empty square => not surrounded
return null;
if (b[xx, yy].IsMine)
{
L.Add(new Point(xx,yy)); // add to queue
mark[xx, yy] = timer; // visited
++tail;
}
}
}
}
}
// the group is surrouneded
return L;
}
This method doesn't use recursion so you don't have to deal with stack overflow (the exception not the site).
You could do it with code that does something like this.
pseudocode
isSurrounded(stone){
//mark that you have seen the stone before
stone.seen = true;
//check if all the surrounding spots are surrounded
for(spot in surrounded.getSpotsAround){
//An empty spot means the stone is not surrounded
if(spot = empty){
return false;
}
else{
//don't recheck stones you have seen before or opponents stones
if(spot.stone.seen != true || !stone.belongsToOpponent){
//recursively call this method, if it returns false your stone is not surrounded
if(!isSurrounded(spot.stone){
return false;
}
}
}
}
//if all of the surrounding stones are surrounded,seen already, or belong to other players, this stone is surrounded
return true;
}
Then you would have to remove all the stones where seen = true or reset seen on all stones.
I came up with this
(Updated)
public List<Point> FindSurrounded(int[,] b, Point p, Player player, List<Point> group)
{
for (int dx = -1; dx <= 1; dx++){
for (int dy = -1; dy <= 1; dy++)
{
//check if group allready contain this spot
if ((dy == 0 || dx == 0) && !(dy == 0 && dx == 0) && !group.Contains(new Point(p.X + dx, p.Y + dy))
{
// is the spot empty
if( b[p.X + dx, p.Y + dy] == 0)
return null;
if(b[p.X + dx, p.Y + dy] == player.Identifier)// is this your own stone
{
//If this is my stone add it to the list and check for it
group.Add( new Point( p.X + dx, p.Y + dy ) );
List<Point> temp = removeSurrounded(b, new Point(p.X + dx, p.Y + dy), player, group);
if(temp == null)
return null;
}
}
}
}
return group;
}
This returns null if there is any empty spot near your group else it will return a list of Points which represents your group.
Afterwards you can remove them like that
List<Point> group = FindSurrounded(b, p, player, new List<Point>());
if(group != null)
foreach(Point point in group)
b[point.x, point.y] = 0;
I've solved Polygon problem problem at interviewstreet, but it seems too slow. What is the best solution to the problem?
There are N points on X-Y plane with integer coordinates (xi, yi). You are given a set of polygons with all of its edges parallel to the axes (in other words, all angles of the polygons are 90 degree angles and all lines are in the cardinal directions. There are no diagonals). For each polygon your program should find the number of points lying inside it (A point located on the border of polygon is also considered to be inside the polygon).
Input:
First line two integers N and Q. Next line contains N space separated integer coordinates (xi,yi). Q queries follow. Each query consists of a single integer Mi in the first line, followed by Mi space separated integer coordinates (x[i][j],y[i][j]) specifying the boundary of the query polygon in clock-wise order.
Polygon is an alternating sequence of vertical line segments and horizontal line segments.
Polygon has Mi edges, where (x[i][j],y[i][j]) is connected to (x[i][(j+1)%Mi], y[i][(j+1)%Mi].
For each 0 <= j < Mi, either x[i][(j+1)%Mi] == x[i][j] or y[i][(j+1)%Mi] == y[i][j] but not both.
It is also guaranteed that the polygon is not self-intersecting.
Output:
For each query output the number of points inside the query polygon in a separate line.
Sample Input #1:
16 2
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
3 0
3 1
3 2
3 3
8
0 0
0 1
1 1
1 2
0 2
0 3
3 3
3 0
4
0 0
0 1
1 1
1 0
Sample Output #1:
16
4
Sample Input #2:
6 1
1 1
3 3
3 5
5 2
6 3
7 4
10
1 3
1 6
4 6
4 3
6 3
6 1
4 1
4 2
3 2
3 3
Sample Output #2:
4
Constraints:
1 <= N <= 20,000
1 <= Q <= 20,000
4 <= Mi <= 20
Each co-ordinate would have a value of atmost 200,000
I am interested in solutions in mentioned languages or pseudo code.
EDIT: here is my code but it's O(n^2)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Polygon
{
// avoding System.Drawing dependency
public struct Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
: this()
{
X = x;
Y = y;
}
public override int GetHashCode()
{
return X ^ Y;
}
public override bool Equals(Object obj)
{
return obj is Point && this == (Point)obj;
}
public static bool operator ==(Point a, Point b)
{
return a.X == b.X && a.Y == b.Y;
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
}
public class Solution
{
static void Main(string[] args)
{
BasicTestCase();
CustomTestCase();
// to read from STDIN
//string firstParamsLine = Console.ReadLine();
//var separator = new char[] { ' ' };
//var firstParams = firstParamsLine.Split(separator);
//int N = int.Parse(firstParams[0]);
//int Q = int.Parse(firstParams[1]);
//List<Point> points = new List<Point>(N);
//for (int i = 0; i < N; i++)
//{
// var coordinates = Console.ReadLine().Split(separator);
// points.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
//}
//var polygons = new List<List<Point>>(Q); // to reduce realocation
//for (int i = 0; i < Q; i++)
//{
// var firstQ = Console.ReadLine().Split(separator);
// int coordinatesLength = int.Parse(firstQ[0]);
// var polygon = new List<Point>(coordinatesLength);
// for (int j = 0; j < coordinatesLength; j++)
// {
// var coordinates = Console.ReadLine().Split(separator);
// polygon.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
// }
// polygons.Add(polygon);
//}
//foreach (var polygon in polygons)
//{
// Console.WriteLine(CountPointsInPolygon(points, polygon));
//}
}
private static void BasicTestCase()
{
List<Point> points = new List<Point>(){ new Point(0, 0),
new Point(0, 1),
new Point(0, 2),
new Point(0, 3),
new Point(1, 0),
new Point(1, 1),
new Point(1, 2),
new Point(1, 3),
new Point(2, 0),
new Point(2, 1),
new Point(2, 2),
new Point(2, 3),
new Point(3, 0),
new Point(3, 1),
new Point(3, 2),
new Point(3, 3) };
List<Point> polygon1 = new List<Point>(){ new Point(0, 0),
new Point(0, 1),
new Point(2, 1),
new Point(2, 2),
new Point(0, 2),
new Point(0, 3),
new Point(3, 3),
new Point(3, 0)};
List<Point> polygon2 = new List<Point>(){ new Point(0, 0),
new Point(0, 1),
new Point(1, 1),
new Point(1, 0),};
Console.WriteLine(CountPointsInPolygon(points, polygon1));
Console.WriteLine(CountPointsInPolygon(points, polygon2));
List<Point> points2 = new List<Point>(){new Point(1, 1),
new Point(3, 3),
new Point(3, 5),
new Point(5, 2),
new Point(6, 3),
new Point(7, 4),};
List<Point> polygon3 = new List<Point>(){ new Point(1, 3),
new Point(1, 6),
new Point(4, 6),
new Point(4, 3),
new Point(6, 3),
new Point(6, 1),
new Point(4, 1),
new Point(4, 2),
new Point(3, 2),
new Point(3, 3),};
Console.WriteLine(CountPointsInPolygon(points2, polygon3));
}
private static void CustomTestCase()
{
// generated 20 000 points and polygons
using (StreamReader file = new StreamReader(#"in3.txt"))
{
string firstParamsLine = file.ReadLine();
var separator = new char[] { ' ' };
var firstParams = firstParamsLine.Split(separator);
int N = int.Parse(firstParams[0]);
int Q = int.Parse(firstParams[1]);
List<Point> pointsFromFile = new List<Point>(N);
for (int i = 0; i < N; i++)
{
var coordinates = file.ReadLine().Split(separator);
pointsFromFile.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
}
var polygons = new List<List<Point>>(Q); // to reduce realocation
for (int i = 0; i < Q; i++)
{
var firstQ = file.ReadLine().Split(separator);
int coordinatesLength = int.Parse(firstQ[0]);
var polygon = new List<Point>(coordinatesLength);
for (int j = 0; j < coordinatesLength; j++)
{
var coordinates = file.ReadLine().Split(separator);
polygon.Add(new Point(int.Parse(coordinates[0]), int.Parse(coordinates[1])));
}
polygons.Add(polygon);
}
foreach (var polygon in polygons)
{
Console.WriteLine(CountPointsInPolygon(pointsFromFile, polygon));
}
}
}
public static int CountPointsInPolygon(List<Point> points, List<Point> polygon)
{
// TODO input check
polygon.Add(polygon[0]); // for simlicity
// check if any point is outside of the bounding box of the polygon
var minXpolygon = polygon.Min(p => p.X);
var maxXpolygon = polygon.Max(p => p.X);
var minYpolygon = polygon.Min(p => p.Y);
var maxYpolygon = polygon.Max(p => p.Y);
// ray casting algorithm (form max X moving to point)
int insidePolygon = 0;
foreach (var point in points)
{
if (point.X >= minXpolygon && point.X <= maxXpolygon && point.Y >= minYpolygon && point.Y <= maxYpolygon)
{ // now points are inside the bounding box
isPointsInside(polygon, point, ref insidePolygon);
} // else outside
}
return insidePolygon;
}
private static void isPointsInside(List<Point> polygon, Point point, ref int insidePolygon)
{
int intersections = 0;
for (int i = 0; i < polygon.Count - 1; i++)
{
if (polygon[i] == point)
{
insidePolygon++;
return;
}
if (point.isOnEdge(polygon[i], polygon[i + 1]))
{
insidePolygon++;
return;
}
if (Helper.areIntersecting(polygon[i], polygon[i + 1], point))
{
intersections++;
}
}
if (intersections % 2 != 0)
{
insidePolygon++;
}
}
}
static class Helper
{
public static bool isOnEdge(this Point point, Point first, Point next)
{
// onVertical
if (point.X == first.X && point.X == next.X && point.Y.InRange(first.Y, next.Y))
{
return true;
}
//onHorizontal
if (point.Y == first.Y && point.Y == next.Y && point.X.InRange(first.X, next.X))
{
return true;
}
return false;
}
public static bool InRange(this int value, int first, int second)
{
if (first <= second)
{
return value >= first && value <= second;
}
else
{
return value >= second && value <= first;
}
}
public static bool areIntersecting(Point polygonPoint1, Point polygonPoint2, Point vector2End)
{
// "move" ray up for 0.5 to avoid problem with parallel edges
if (vector2End.X < polygonPoint1.X )
{
var y = (vector2End.Y + 0.5);
var first = polygonPoint1.Y;
var second = polygonPoint2.Y;
if (first <= second)
{
return y >= first && y <= second;
}
else
{
return y >= second && y <= first;
}
}
return false;
}
}
}
A faster solution is to place the points into a quadtree.
A region quadtree might be easier to code, but a point quadtree is probably faster. If using a region quadtree then it can help to stop subdividing the quadtree when the number of points in a quad falls below a threshold (say 16 points)
Each quad stores the number of points it contains, plus either a list of coordinates (for leaf nodes) or pointers to smaller quads. (You can omit the list of coordinates when the size of the quad reaches 1 as they must all be coincident)
To count the points inside the polygon you look at the largest quad that represents the root of the quadtree.
Clip the polygon to the edges of the quad
If the polygon does not overlap the quad then return 0
If this is a quad of size 1x1 then return the number of points in the quad
If the polygon totally encircles the quad then return the number of points in the quad.
If this is a leaf node then test each point with the plumb line algorithm
Otherwise recursively count the points in each child quad
(If a quad only has one non-empty child then you can skip steps 1,2,3,4,5 to go a little faster)
(The tests in 2 and 4 do not have to be totally accurate)
Does trapezoidal decomposition work for you?
I refer you to Jordan Curve Theorem and the Plumb Line Algorithm.
The relevant pseudocode is
int crossings = 0
for (each line segment of the polygon)
if (ray down from (x,y) crosses segment)
crossings++;
if (crossings is odd)
return (inside);
else return (outside);
I would try casting a ray up from the bottom to each point, tracking where it crossed into the polygon (passing a right-to-left segment) or back out of the polygon (passing a left-to-right segment). Something like this:
count := 0
For each point (px, py):
inside := false
For each query line (x0, y0) -> (x1, y1) where y0 = y1
if inside
if x0 <= px < x1 and py > y0
inside = false
else
if x1 <= px <= x0 and py >= y0
inside = true
if inside
count++
The > vs. >= in the two cases is so that a point on the upper edge is considered inside. I haven't actually coded this up to see if it works, but I think the approach is sound.
Here is the solution from authors - a bit obfuscated, isn't it?
#include <iostream>
#include <ctime>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <ctime>
using namespace std;
typedef long long int64;
const int N = 100000, X = 2000000001;
const int Q = 100000, PQ = 20;
struct Point {
int x, y, idx;
Point(int _x = 0, int _y = 0, int _idx = 0) {
x = _x;
y = _y;
idx = _idx;
}
} arr_x[N], arr_y[N];
struct VLineSegment {
int x, y1, y2, idx, sign;
VLineSegment(int _x = 0, int _y1 = 0, int _y2 = 0, int _sign = 1, int _idx = 0) {
x = _x;
y1 = _y1;
y2 = _y2;
sign = _sign;
idx = _idx;
}
bool operator<(const VLineSegment& v) const {
return x < v.x;
}
} segs[Q * PQ];
struct TreeNode {
int idx1, idx2, cnt;
TreeNode *left, *right;
TreeNode() { left = right = 0; cnt = 0; }
~TreeNode() { if(left) delete left; if(right) delete right; }
void update_stat() {
cnt = left->cnt + right->cnt;
}
void build(Point* arr, int from, int to, bool empty) {
idx1 = from;
idx2 = to;
if(from == to) {
if(!empty) {
cnt = 1;
} else {
cnt = 0;
}
} else {
left = new TreeNode();
right = new TreeNode();
int mid = (from + to) / 2;
left->build(arr, from, mid, empty);
right->build(arr, mid + 1, to, empty);
update_stat();
}
}
void update(Point& p, bool add) {
if(p.idx >= idx1 && p.idx <= idx2) {
if(idx1 != idx2) {
left->update(p, add);
right->update(p, add);
update_stat();
} else {
if(add) {
cnt = 1;
} else {
cnt = 0;
}
}
}
}
int query(int ya, int yb) {
int y1 = arr_y[idx1].y, y2 = arr_y[idx2].y;
if(ya <= y1 && y2 <= yb) {
return cnt;
} else if(max(ya, y1) <= min(yb, y2)) {
return left->query(ya, yb) + right->query(ya, yb);
}
return 0;
}
};
bool cmp_x(const Point& a, const Point& b) {
return a.x < b.x;
}
bool cmp_y(const Point& a, const Point& b) {
return a.y < b.y;
}
void calc_ys(int x1, int y1, int x2, int y2, int x3, int sign, int& ya, int& yb) {
if(x2 < x3) {
yb = 2 * y2 - sign;
} else {
yb = 2 * y2 + sign;
}
if(x2 < x1) {
ya = 2 * y1 + sign;
} else {
ya = 2 * y1 - sign;
}
}
bool process_polygon(int* x, int* y, int cnt, int &idx, int i) {
for(int j = 0; j < cnt; j ++) {
//cerr << x[(j + 1) % cnt] - x[j] << "," << y[(j + 1) % cnt] - y[j] << endl;
if(x[j] == x[(j + 1) % cnt]) {
int _x, y1, y2, sign;
if(y[j] < y[(j + 1) % cnt]) {
_x = x[j] * 2 - 1;
sign = -1;
calc_ys(x[(j + cnt - 1) % cnt], y[j], x[j], y[(j + 1) % cnt], x[(j + 2) % cnt], sign, y1, y2);
} else {
_x = x[j] * 2 + 1;
sign = 1;
calc_ys(x[(j + 2) % cnt], y[(j + 2) % cnt], x[j], y[j], x[(j + cnt - 1) % cnt], sign, y1, y2);
}
segs[idx++] = VLineSegment(_x, y1, y2, sign, i);
}
}
}
int results[Q];
int n, q, c;
int main() {
int cl = clock();
cin >> n >> q;
for(int i = 0; i < n; i ++) {
cin >> arr_y[i].x >> arr_y[i].y;
arr_y[i].x *= 2;
arr_y[i].y *= 2;
}
int idx = 0, cnt, x[PQ], y[PQ];
for(int i = 0; i < q; i ++) {
cin >> cnt;
for(int j = 0; j < cnt; j ++) cin >> x[j] >> y[j];
process_polygon(x, y, cnt, idx, i);
}
sort(segs, segs + idx);
memset(results, 0, sizeof results);
sort(arr_y, arr_y + n, cmp_y);
for(int i = 0; i < n; i ++) {
arr_y[i].idx = i;
arr_x[i] = arr_y[i];
}
sort(arr_x, arr_x + n, cmp_x);
TreeNode tleft;
tleft.build(arr_y, 0, n - 1, true);
for(int i = 0, j = 0; i < idx; i ++) {
for(; j < n && arr_x[j].x <= segs[i].x; j ++) {
tleft.update(arr_x[j], true);
}
int qcnt = tleft.query(segs[i].y1, segs[i].y2);
//cerr << segs[i].x * 0.5 << ", " << segs[i].y1 * 0.5 << ", " << segs[i].y2 * 0.5 << " = " << qcnt << " * " << segs[i].sign << endl;
results[segs[i].idx] += qcnt * segs[i].sign;
}
for(int i = 0; i < q; i ++) {
cout << results[i] << endl;
}
cerr << (clock() - cl) * 0.001 << endl;
return 0;
}