走迷宫

走迷宫,注意那两个getchar,第二个getchar是为了接受换行符。

#include <stdio.h>
#include <stdlib.h>

void show(int a[10][10])
{
    printf("----------------------------
");
    for (int i = 0; i < 10;i++)
    {
        for (int j = 0; j < 10;j++)
        {
            printf("%3d", a[i][j]);
        }
        printf("
");
    }
}


void main()
{
    int a[10][10] = { 
                       {,  0, 0, 2,  0,  0,  0,0,0,0 },
                       { 0, 0, 2, 0 , 0, 0, 0, 0, 0,0 }, 
                       { 0, 0, 2, 2, 2, 0, 0, 0, 0, 0 },
                       { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 
                       { 0, 0, 0, 0, 2, 0, 0, 0, 0, 0 },
                       { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 
                       { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 
                       { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 
                       { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 
                       { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 }, 
            }; show(a);
int x, y; x = 0; y = 0; a[x][y] = 1; show(a); while (1) { char ch = getchar(); getchar();//回车 switch (ch) { case 'a': if (y - 1 >= 0 && a[x][y - 1]!=2) { int temp = a[x][y - 1]; a[x][y - 1] = a[x][y]; a[x][y] = temp; y = y - 1; } break; case 'd': if (y + 1 <= 9 && a[x][y + 1] != 2) { int temp = a[x][y +1]; a[x][y + 1] = a[x][y]; a[x][y] = temp; y = y + 1; } break; case 'w': if (x - 1 >= 0 && a[x-1][y ] != 2) { int temp = a[x-1][y]; a[x-1][y ] = a[x][y]; a[x][y] = temp; x-=1; } break; case 's': if (x + 1 <= 9 && a[x + 1][y] != 2) { int temp = a[x + 1][y]; a[x + 1][y] = a[x][y]; a[x][y] = temp; x += 1; } break; default: break; } show(a); } system("pause"); }
原文地址:https://www.cnblogs.com/sjxbg/p/5617355.html