Last active
January 14, 2020 10:13
-
-
Save hulefei/a43bb87ccb2493ef36b84eae71e2a399 to your computer and use it in GitHub Desktop.
Maze 算法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Maze | |
{ | |
class Step{ | |
public int x,y,d; | |
public Step(int x,int y,int d) { | |
this.x = x;//横坐标 | |
this.y = y;//纵坐标 | |
this.d = d;//方向 | |
} | |
} | |
private Stack s; | |
int[,] maze = | |
{ //0 1 2 3 4 5 6 7 8 9 | |
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, // 0 | |
{1, 0, 1, 1, 1, 0, 1, 1, 1, 1}, // 1 | |
{1, 1, 0, 1, 0, 1, 1, 1, 1, 1}, // 2 | |
{1, 0, 1, 0, 0, 0, 0, 0, 1, 1}, // 3 | |
{1, 0, 1, 1, 1, 0, 1, 1, 1, 1}, // 4 | |
{1, 1, 0, 0, 1, 1, 0, 0, 0, 1}, // 5 | |
{1, 0, 1, 1, 0, 0, 1, 1, 0, 1}, // 6 | |
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1} // 7 | |
}; | |
int[,] move = {{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; | |
public Maze() | |
{ | |
s = new Stack(); | |
} | |
public void Result() | |
{ | |
while(s.Count != 0){ | |
Step step = s.Peek() as Step; | |
Console.WriteLine(step.x+","+step.y); | |
} | |
} | |
public int path(){ | |
Step temp = new Step(1,1,-1); //起点 | |
s.Push(temp); | |
while(s.Count != 0) | |
{ | |
temp = s.Pop() as Step; | |
int x = temp.x; | |
int y = temp.y; | |
int d = temp.d+1; | |
while(d<8){ | |
int i = x + move[d, 0]; | |
int j = y + move[d, 1]; | |
if(maze[i,j] == 0){ //该点可达 | |
temp = new Step(i,j,d); //到达新点 | |
s.Push(temp); | |
x = i; | |
y = j; | |
maze[x, y] = -1; //到达新点,标志已经到达 | |
if(x == 6 && y == 8){ | |
return 1; //到达出口,迷宫有路,返回1 | |
}else{ | |
d = 0; //重新初始化方向 | |
} | |
}else{ | |
d++; //改变方向 | |
} | |
} | |
//所有方向尝试失败后,推出顶端数据 | |
s.Pop(); | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment