poj 1573 Robot Motion(java 模拟)

来源:互联网 发布:广州seo顾问 编辑:程序博客网 时间:2024/06/05 10:27
package test;

import java.util.Scanner;

/**问题请参考http://poj.org/problem?id=1573
 * @author rayli

 * @date:2014-7-23 上午8:37:07
 * 题意 :模拟一个机器人在特定的棋盘中行走,每个棋盘的格子规定好了机器人移动的方向,每次移动只能走一个格子,
 * 问机器人退出棋盘时走的步数,如果不能退出棋盘,
 * 输出机器人进入循环前走的步数和每次循环中包含的步数。
 *
 */
public class RobotMotion
{
    static char simu[][];//命令集
    int vist[][];//用来标记走过的路径
    static int r;
    static int c;
    int step;
    
    void init()
    {
        simu = new char[r][c];
        vist = new int[r+1][c+1];
        /**
         * /刚开始step是从0开始计算的,把开始位置设置为0了,导致在出显
         * 2 1 1
         * S
         * N
         * 1 step(s) before a loop of 2 step(s)而不是
         * 正确答案 0 step(s) before a loop of 2 step(s)
         */
        step = 1;
    }
    
    //用来判断有没有走出棋盘
    boolean judge(int i, int j)
    {
        if(i>=0 && i<r && j>=0 && j<c)
            return true;
        else
            return false;
    }
    
    void simulate(int j)
    {
        int i = 0;
        boolean flag = true;
        
        while(judge(i, j))
        {
            if(vist[i][j] != 0)
            {
                flag = false;
                break;
            }
            else
            {
                vist[i][j] = step;
                char tmp = simu[i][j];
                
                switch(tmp)
                {
                    case 'N':
                        i--;
                        break;
                    case 'S':
                        i++;
                        break;
                    case 'W':
                        j--;
                        break;
                    case 'E':
                        j++;
                        break;
                }
            }
            step++;        
        }
        
        if(flag)
        {
            System.out.println((step - 1) + " step(s) to exit");
            return;
        }
        else
        {
            System.out.println((vist[i][j]-1) + " step(s) before a loop of " + (step - vist[i][j]) + " step(s)");
            return;
        }
    }
    
    public static void main(String args[])
    {
        Scanner cin = new Scanner(System.in);
         r = cin.nextInt();//命令集的行数
         c = cin.nextInt();//命令集的列数
         int d = cin.nextInt();//机器人开始的位置,在第0行d-1列
        
        while(r !=0 && c != 0 && d != 0)
        {
            RobotMotion rm = new RobotMotion();
            
            //对数组进行初始化
            rm.init();
            
            //输入命令集
            for(int i=0; i<r; i++)
                simu[i] = cin.next().toCharArray();
            
            //根据命令集进行模拟
            //结果输出
            rm.simulate(d - 1);
            
            r = cin.nextInt();
            c = cin.nextInt();
            d = cin.nextInt();
        }
        
        cin.close();
    }
}