-2

Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?

Input format

The first line contains an odd integer N (3 <= N < 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by '-' (ascii value: 45). The bot position is denoted by 'm' and the princess position is denoted by 'p'.

Grid is indexed using Matrix Convention

Output format

Print out the moves you will take to rescue the princess in one go. The moves must be separated by '\n', a newline. The valid moves are LEFT or RIGHT or UP or DOWN.

Here is my code:

package challenges;

import java.util.*;

public class Solution {
static void displayPathtoPrincess(int n, int p,String [][] grid){
int botRow=0,botCol=0;

for(int r=0;r<n;r++){
   for (int c = 0; c < grid.length; c++) {
        if(grid[r][c].equals('m')) {
            botRow=r;
            botCol=c;
            continue;
        }
   }
        if(grid[0][0].equals('P')) {
            while(botRow>0) {
                botRow--;
                System.out.println("UP\n");
            }
            while(botCol>0) {
                botCol--;
                System.out.println("LEFT\n");
            }
        }
        else if(grid[0][p-1].equals('P')) {
            while(botRow>0) {
                System.out.println("UP\n");
                botRow--;
            }
            while(botCol<p-1) {
                botCol++;
                System.out.println("RIGHT\n");
            }
        }
        else if(grid[n-1][0].equals('P')) {
            while(botRow<n-1) {
                botRow++;
                System.out.println("DOWN\n");
            }
            while(botCol>0) {
                botCol--;
                System.out.println("LEFT\n");
            }
        }
        else if(grid[n-1][p-1].equals('P')) {
            while(botRow<n-1) {
                botRow++;
                System.out.println("DOWN\n");
            }
            while(botCol<p-1) {
                botCol++;
                System.out.println("RIGHT\n");
            }
        }   
   }
}
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int m,n;
    m = in.nextInt();
    n=m;
    int j=0;
    String grid[][] = new String[m][n];
    for(int i = 0; i < m; i++) {
       while(j<n){
            grid[i][j] = in.next();             
        j++;
       }     
    }

displayPathtoPrincess(m,n,grid);

}
}

Its giving Null Pointer Exception.can anyone please tel what am i doing wrong in here?

4

6 回答 6

2

试试这个解决方案:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int m = Integer.parseInt(br.readLine());

        char grid[][] = new char[m][m];
        for(int i = 0; i < m; i++)
        {
            String line = br.readLine();
            grid[i] = (line.trim()).toCharArray();
        }

        displayPathtoPrincess(m, grid);
    }

    static void displayPathtoPrincess(int m, char[][] grid)
    {
        int botRow = 0, botCol = 0, princessRow = 0, princessCol = 0;

        // Get bot and princess coordinates
        for (int r = 0; r < m; r++)
        {
            for (int c = 0; c < grid.length; c++)
            {
                if (grid[r][c] == 'm' || grid[r][c] == 'M')
                {
                    botRow = r;
                    botCol = c;
                }
                else if (grid[r][c] == 'p' || grid[r][c] == 'P')
                {
                    princessRow = r;
                    princessCol = c;
                }
            }
        }

        // Move the bot up or down till bot reaches same row
        if( princessRow < botRow )
        {
            while(botRow != princessRow)
            {
                botRow--;
                System.out.println("UP");
            }
        }
        else if( princessRow > botRow )
        {
            while(botRow != princessRow)
            {
                botRow++;
                System.out.println("DOWN");
            }
        }

        // Move the bot left or right till bot reaches same column
        if( princessCol < botCol )
        {
            while(botCol != princessCol)
            {
                botCol--;
                System.out.println("LEFT");
            }
        }
        else if( princessCol > botCol )
        {
            while(botCol != princessCol)
            {
                botCol++;
                System.out.println("RIGHT");
            }
        }

    }
}
于 2017-01-10T10:44:16.630 回答
2

好的,没有冒犯,但这段代码是一团糟。

我知道我将回答的内容不会完全符合您的要求,但将来可能对您很有帮助。

我会改变什么?(在您更改所有这些之后,错误将更有可能变得明显,或者它会足够清楚以寻求帮助)

第一:变量类型。

这只是一个小细节,但我不喜欢你这样做的方式;如果每个单元格都由一个字符表示,为什么要使用字符串?

每次创建变量(或数组,或任何东西)时,请考虑您需要它存储什么,并以一种可以存储您需要的方式创建变量。如果您需要它来存储某些东西是true还是false,则不会创建 String 变量并存储"true""false",而是使用布尔值。

每次都应用这个,你会进步得更快。

第二:使用功能。

函数是将自己从实现细节中抽象出来的好方法。

我的意思是,您可以很容易地看到您的代码之类的内容与以下内容之间的区别:

static void displayPathtoPrincess(int n, int p,char [][] grid){

    Point bot;
    Point princess;

    getInitialPositions(bot, princess, grid);

    Point dif = getRelativePrincessPosition(bot, princess);

    while (!bot.equals(princess)) {
        switch (dif.y) {
            case UP:
                move (UP_MOVEMENT);
                break;
            case DOWN:
                move (DOWN_MOVEMENT);
                break;
        }
        switch (dif.x) {
            case LEFT:
                move(LEFT_MOVEMENT);
                break;
            case RIGHT:
                move(RIGHT_MOVEMENT);
                break;
        }
    }
}

(然后实现必要的方法,并创建常量,这很容易做到)

第三:每次都使用合适的循环。

如果您知道要从 j = 0 开始,而 j < n,则每次迭代都增加 j;那不叫 a while,那叫 a for。(另外,正如其他人在他们的回答中评论的那样,您忘记重新启动j;所以它只进入一次。

最后:让我们现在解决您的错误。

我相信您的代码可能有很多错误并且没有给您所需的输出,但 NullPointerException 是更具体的东西。

由于您没有在 main, for j中使用适当的循环,并且您忘记重新启动它的值,因此您没有填充整个数组。

当您尝试读取未填写的值时(在您找到机器人位置的 for 中),该值为null,并且某些行的值也将为null;因此 NullPointerException (因为您尝试访问空数组的值)。

于 2016-04-11T11:26:03.850 回答
0

您可能希望查看以下 Java 代码:

import java.util.Scanner;

public class Solution {

    /*
     * 
     */
    static void printPath(int n, String moves) {
        for (int i = n / 2; i >= 0; i -= 2) {
            System.out.println(moves);
        }           
    }
    
    /*
     * 
     */
    static void displayPathtoPrincess(int n, String [] grid){

        // **** princess @ top left  ****
        
        if (grid[0].substring(0, 1).equals("p")) {
            printPath(n, "UP\nLEFT");
        }
        
        // **** princess @ top right ****
        
        else if (grid[0].substring(n - 1, n).equals("p") ) {
            printPath(n, "UP\nRIGHT");
        }
        
        // **** princess @ bottom right ****
            
        else if (grid[n - 1].substring(n - 1, n).equals("p")) {
            printPath(n, "DOWN\nRIGHT");
        }
        
        // **** princess @ bottom left ****
        
        else {
            printPath(n, "DOWN\nLEFT");
        }
    }

    /*
     * Test code
     */
    public static void main(String[] args) {
        
        Scanner in = new Scanner(System.in);
        int m;
        m = in.nextInt();
        String grid[] = new String[m];
        
        for(int i = 0; i < m; i++) {
            grid[i] = in.next();
        }

        // **** ****
        
        in.close();
        
        // **** ****
        
        displayPathtoPrincess(m,grid);
    }
}
于 2017-02-13T21:41:21.887 回答
0

在接受输入时,每次退出 while 循环时都必须使 j =0

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int m,n;
    m = in.nextInt();
    n=m;
    int j=0;
    String grid[][] = new String[m][n];
    for(int i = 0; i < m; i++) {
       j = 0;
       while(j<n){
            grid[i][j] = in.next();             
        j++;
       }     
    }

由于这个错误,我仍然为 0。您应该放置打印语句来检查为什么会出错。

于 2016-04-11T11:07:12.517 回答
0
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

static void nextMove(int n, int r, int c, String  [] grid){

int xcord=0;
int ycord=0;
for ( int i = 0 ; i <n-1; i++){
    String s = grid[i];
    xcord=i;
    for(int x =0; x<=n-1;x++){
        if(s.charAt(x)=='p'){
            ycord=x;
            
            if(xcord==r){
                if(ycord>c){System.out.println("RIGHT");return;}
                else {System.out.println("LEFT");return;}
                
            }else if(xcord<r){System.out.println("UP");return;}
           
            else{ System.out.println("DOWN");return;}
              
            
        }
        
        
    }
  

 }

 System.out.println(xcord);
System.out.println(ycord);
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n,r,c;
    n = in.nextInt();
    r = in.nextInt();
    c = in.nextInt();
    in.useDelimiter("\n");
    String grid[] = new String[n];


    for(int i = 0; i < n; i++) {
        grid[i] = in.next();
    }

  nextMove(n,r,c,grid);

  }
}
于 2020-10-19T06:22:02.277 回答
0

这是解决方案..

import java.util.*;

public class Solution {
static void displayPathtoPrincess(int n, int p, String[][] grid) {
    int botRow = 0, botCol = 0;

    for (int r = 0; r < n; r++) {
        for (int c = 0; c < grid.length; c++) {
            if (grid[r][c].equalsIgnoreCase("m")) {
                botRow = r;
                botCol = c;
            }
        }
        if (grid[0][0].equalsIgnoreCase("P")) {
            while (botRow > 0) {
                botRow--;
                System.out.println("UP\n");
            }
            while (botCol > 0) {
                botCol--;
                System.out.println("LEFT\n");
            }
        } else if (grid[0][p - 1].equalsIgnoreCase("P")) {
            while (botRow > 0) {
                botRow--;
                System.out.println("UP\n");
            }
            while (botCol < p - 2) {
                botCol++;
                System.out.println("RIGHT\n");
            }
        } else if (grid[n - 1][0].equalsIgnoreCase("P")) {
            while (botRow < n - 2) {
                botRow++;
                System.out.println("DOWN\n");
            }
            while (botCol > 0) {
                botCol--;
                System.out.println("LEFT\n");
            }
        } else if (grid[n - 1][p - 1].equalsIgnoreCase("P")) {
            while (botRow < n - 2) {
                botRow++;
                System.out.println("DOWN\n");
            }
            while (botCol < p - 2) {
                botCol++;
                System.out.println("RIGHT\n");
            }
        }
    }
}
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int m,n;
    m = in.nextInt();

    int j;
    String grid[][] = new String[m][m];
    for(int i = 0; i < m; i++) {

       for(j=0;j<m;j++){
            grid[i][j] = in.next();             

       }     
    }

displayPathtoPrincess(m,m,grid);

}
}
于 2016-04-11T12:51:22.417 回答