【IT面试题006】迷宫问题
/* 迷宫问题 1 表示可以走 0 表示不可以走 */ #include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; int pathX[1000]; int pathY[1000]; int curPathPointNum; int gPathCount = 0; int visited[10][10] = {0}; int maze[10][10] = {0}; int minPathLen = 1000000000; void InitMaze() { maze[1][1]=1; maze[1][2]=1; maze[1][4]=1; maze[1][5]=1; maze[1][6]=1; maze[1][8]=1; maze[2][1]=1; maze[2][2]=1; maze[2][4]=1; maze[2][5]=1; maze[2][6]=1; maze[2][8]=1; maze[3][1]=1; maze[3][2]=1; maze[3][3]=1; maze[3][4]=1; maze[3][7]=1; maze[3][8]=1; maze[4][1]=1; maze[4][5]=1; maze[4][6]=1; maze[4][7]=1; maze[4][8]=1; maze[5][1]=1; maze[5][2]=1; maze[5][3]=1; maze[5][5]=1; maze[5][6]=1; maze[5][7]=1; maze[5][8]=1; maze[6][1]=1; maze[6][3]=1; maze[6][4]=1; maze[6][5]=1; maze[6][7]=1; maze[6][8]=1; maze[7][1]=1; maze[7][5]=1; maze[7][8]=1; maze[8][2]=1; maze[8][3]=1; maze[8][4]=1; maze[8][5]=1; maze[8][6]=1; maze[8][7]=1; maze[8][8]=1; } void PrintPath() { for (int i = 0;i<curPathPointNum;i++) { cout << "(" << pathX[i] <<","<<pathY[i]<<")"<<" "; } cout << endl; } void Go(int posX,int posY,int endX,int endY) { if (posX == endX && posY == endY) { if (curPathPointNum - 1 < minPathLen) { minPathLen = curPathPointNum - 1; } cout << "found a path"<<endl; gPathCount ++; PrintPath(); return; } if (curPathPointNum - 1 >= minPathLen) { return; } static int dx[4] = {1,-1,0,0}; static int dy[4] = {0,0,1,-1}; for (int i = 0;i<4;i++) { int newX = posX + dx[i]; int newY = posY + dy[i]; if (maze[newX][newY] == 1 && !visited[newX][newY]) { curPathPointNum ++; visited[newX][newY] = 1; pathX[curPathPointNum - 1] = newX; pathY[curPathPointNum - 1] = newY; Go(newX,newY,endX,endY); visited[newX][newY] = 0; curPathPointNum --; } } } int _tmain(int argc, _TCHAR* argv[]) { InitMaze(); int startX = 1; int startY = 0; int endX = 8; int endY = 8; curPathPointNum = 0; Go(startX,startY,endX,endY); cout << gPathCount << endl; }
posted on 2011-06-04 20:22 speedmancs 阅读(304) 评论(0) 编辑 收藏 举报