HDOJ 1035 模拟 水
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1035
稍微有点复杂,但是只要模拟出来应该就能过了。
#include <iostream> using namespace std; class node { public: char instruct; int stepId; }; const int SIZE = 12; char aLine[SIZE]; node map[SIZE][SIZE]; void move(int &curRow,int &curCol,char instruct) { switch (instruct) { case 'N': curRow --; break; case 'S': curRow ++; break; case 'W': curCol --; break; case 'E': curCol ++; break; } } //计算从起始点(1,initCol)走到(endRow,endCol)需要走多个步 int countStepBeforeExit(int initCol,int endRow,int endCol) { int curRow = 1,curCol = initCol; int stepBeforeExit = 0; while (1) { if (curRow == endRow && curCol == endCol) break; stepBeforeExit ++; move(curRow,curCol,map[curRow][curCol].instruct); } return stepBeforeExit; } //判断(curRow,curCol)是否出界 int judgeExit(int curRow,int curCol,int row,int col) { if (curRow < 1 || curRow > row || curCol < 1 || curCol > col) return 1; return 0; } int main () { int row,col,initCol; while (scanf("%d%d%d",&row,&col,&initCol) != -1) { if (row == 0 && col == 0 && initCol == 0) break; //初始化 for (int i = 0;i < SIZE;i ++) for (int j = 0;j < SIZE;j ++) map[i][j].stepId = 0; for (int i = 1;i <= row;i ++) { scanf("%s",aLine); for (int j = 1;j <= col;j ++) { map[i][j].instruct = aLine[j - 1]; } } int isExit = 1,stepBeforeExit,stepLoop; int preRow,preCol; preRow = preCol = -1; int curRow = 1,curCol = initCol; int stepCount = 0; while (1) { //这一点之前曾走过,说明出现了回路 if (map[curRow][curCol].stepId != 0) { stepLoop = map[preRow][preCol].stepId - map[curRow][curCol].stepId + 1; //计算走到当前点的前一点用了多少个step(s) stepBeforeExit = countStepBeforeExit(initCol,curRow,curCol); //最后没能走出去 isExit = 0; break; } else if (judgeExit(curRow,curCol,row,col)) { isExit = 1; stepBeforeExit = map[preRow][preCol].stepId; break; } stepCount ++; map[curRow][curCol].stepId = stepCount; preRow = curRow , preCol = curCol; //走到下一点 move(curRow,curCol,map[curRow][curCol].instruct); } //能走出去 if (isExit) printf("%d step(s) to exit\n",stepBeforeExit); else printf("%d step(s) before a loop of %d step(s)\n",stepBeforeExit,stepLoop); } return 0; }

浙公网安备 33010602011771号