一点一点分析的话还是能做出来的 import java.util.ArrayList; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String operators = scanner.nextLine(); int rowsAndColumns = scanner.nextInt(); int row = rowsAndColumns / 10; int column = rowsAndColumns % 10; String[][] board = new String[row][column]; ArrayList<path> snake = new ArrayList<>(); for (int i = 0; i < board.length; i++) { String temp = scanner.next(); for (int j = 0; j < board[0].length; j++) { if("H".equals(temp.substring(j))){ snake.add(new Path(i,j,"L")); } board[i][j] = temp.substring(j,j+1); } } for (int i = 0; i < operators.length(); i++) { char operator = operators.charAt(i); if(operator == 'U'){ snake.get(0).setDirection("U"); }else if(operator == 'D'){ snake.get(0).setDirection("D"); }else if(operator == 'L'){ snake.get(0).setDirection("L"); }else if(operator == 'R'){ snake.get(0).setDirection("R"); }else { //G //移动 move(board,snake); } } } } public static void move(String[][] board,ArrayList<path> snake){ Path head = snake.get(0); String direction = head.getDirection(); int row = 0; int column = 0; if(direction.equals("U")){ row = head.getRow() - 1; column = head.getColumn(); }else if (direction.equals("L")){ row = head.getRow(); column = head.getColumn()-1; }else if (direction.equals("R")){ row = head.getRow(); column = head.getColumn()+1; }else if (direction.equals("D")){ row = head.getRow()+1; column = head.getColumn(); } //越界,游戏结束 if(row > board.length-1 || column > board[0].length-1){ System.out.println(snake.size()); return; } //碰到自己了 for (int i = 1; i < snake.size()-1; i++) { if(row == snake.get(i).getRow() && column == snake.get(i).getColumn()){ System.out.println(snake.size()); return; } } //碰到食物了 if(board[row][column].equals("F")){ snake.add(0,new Path(row,column,direction)); return; } //正常运动 snake.add(0,new Path(row,column,direction)); snake.remove(snake.size()-1); } } class Path{ int row; int column; String direction; public Path(int row, int column, String direction) { this.row = row; this.column = column; this.direction = direction; } public int getRow() { return row; } public void setRow(int row) { this.row = row; } public int getColumn() { return column; } public void setColumn(int column) { this.column = column; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } }</path></path>
点赞

相关推荐

牛客网
牛客企业服务