【 OJ 】 HDOJ1035 18年11月17日14:15 [ 32 ]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QingCoffe/article/details/84186007

本题也没啥说的....按照题目模拟就行了,读取到啥就怎么走,遇到边界或者循环就出,用visit记录访问过的点,然后读取的每一个点都入栈(可用数组来模拟),如果突然读取到了已经访问过的点说明进入了循环,就去数组栈中找这个重复点,之前点数目为未循环步数,之后点数目为循环数目。

AC代码:

#include <iostream>
using namespace std;
char map[100][100];//地图大小开100
bool visit[100][100];
char d[4] = { 'E','S','W','N' };
int dri[4][2] = { { 0,1 },{ 1, 0 },{ 0, -1 },{ -1, 0 } };
struct p{
    int x;
    int y;
}cp;
p stack[100];
int main(void) {
    int r,c, s;
    cin >> r >> c >> s;
    int i, j,index;
    int step = 0;
    while (c || r) {
        index = step = 0;
        memset(visit, 0, sizeof(visit));
        for (i = 0; i < r; i++) {
            for (j = 0; j < c; ++j) {
                cin >> map[i][j];
            }
        }//录入地图信息
        if (s > c)
            continue;//越界
        //按题目模拟
        cp.x = 0; cp.y = s - 1;
        while (((cp.x >= 0 && cp.x < r) && (cp.y >= 0 && cp.y < c)) && !visit[cp.x][cp.y]) {//在范围内并且为被访问
            stack[index++] = cp;
            visit[cp.x][cp.y] = 1;
            for (i = 0; i < 4; i++) {
                if (map[cp.x][cp.y] == d[i]) {
                    cp.x += dri[i][0];
                    cp.y += dri[i][1];
                    break;
                }//方向转变
            }
        }//出来有2种情况 1 越界  2 循环
        if (cp.x >= 0 && cp.x < r&&cp.y >= 0 && cp.y < c) {//在范围内就是循环
            for (i = 0; i < index; ++i) {
                if (stack[i].x == cp.x&&stack[i].y == cp.y) {
                    step = i ;
                    break;
                }
            }//找出循环step
            cout << step << " step(s) before a loop of " << index - step << " step(s)" << endl;
        }
        else {//循环
            step = index;
            cout << step << " step(s) to exit" << endl;
        }
        cin >> r >> c >> s;
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/QingCoffe/article/details/84186007