1.年终奖
小东所在公司要发年终奖,而小东恰好获得了最高福利,他要在公司年会上参与一个抽奖游戏,游戏在一个6*6的棋盘上进行,上面放着36个价值不等的礼物,每个小的棋盘上面放置着一个礼物,他需要从左上角开始游戏,每次只能向下或者向右移动一步,到达右下角停止,一路上的格子里的礼物小东都能拿到,请设计一个算法使小东拿到价值最高的礼物。
给定一个6*6的矩阵board,其中每个元素为对应格子的礼物价值,左上角为[0,0],请返回能获得的最大价值,保证每个礼物价值大于100小于1000。
import java.util.*;
public class Bonus {
public int getMost(int[][] board) {
int len1 = board.length;
int len2 = board[0].length;
//处理第一行
for(int i = 1; i < len1;i++){
board[0][i] += board[0][i-1];
}
//处理第一列
for(int i = 1; i < len2;i++){
board[i][0] += board[i-1][0];
}
//处理剩下的情况
for(int i = 1; i < len1;i++){
for(int j = 1; j < len2;j++){
board[i][j] += Math.max(board[i-1][j],board[i][j-1]);
}
}
return board[len1-1][len2-1];
}
}
2.迷宫问题
描述
定义一个二维数组 N*M ,如 5 × 5 数组下所示:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的路线。入口点为[0,0],既第一格是可以走的路。
数据范围: 2 \le n,m \le 10 \2≤n,m≤10 , 输入的内容只包含 0 \le val \le 1 \0≤val≤1
输入描述:
输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。
输出描述:
左上角到右下角的最短路径,格式如样例所示。
示例1
输入:
5 5 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
输出:
(0,0) (1,0) (2,0) (2,1) (2,2) (2,3) (2,4) (3,4) (4,4)
示例2
输入:
5 5 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 1 1 0 0 0 0 0 0
输出:
(0,0) (1,0) (2,0) (3,0) (4,0) (4,1) (4,2) (4,3) (4,4)
说明:
注意:不能斜着走!!
import java.util.*;
class Node{
int x;
int y;
public Node(int x,int y){
this.x = x;
this.y = y;
}
}
public class Main{
public static void main(String[] args){
Scanner sca = new Scanner(System.in);
while(sca.hasNext()){
int row = sca.nextInt();
int col = sca.nextInt();
//创建迷宫矩阵
int[][] mat = new int[row][col];
for(int i = 0;i < row;i++){
for(int j = 0; j < col;j++){
mat[i][j] = sca.nextInt();
}
}
//存储路径
ArrayList<Node> path = new ArrayList<>();
//存储最短路径
ArrayList<Node> minpath = new ArrayList<>();
int[][] book = new int[row][col];
Getminpath(mat,row,col,0,0,book,path,minpath);
//打印最短路径
for(Node n : minpath){
System.out.println("(" + n.x +","+ n.y + ")");
}
}
}
public static void Getminpath(int[][] mat,int row,int col,int x,int y,
int[][]book,ArrayList<Node>path,ArrayList<Node>minpath){
//1.判断(x,y)是否越界,是否已经走过,是否有障碍
if(x < 0 || x >= row || y < 0 || y >= col || book[x][y] == 1 || mat[x][y] == 1){
return;
}
//2.先把当前位置存入路径中,并设置为已走
path.add(new Node(x,y));
//标记矩阵,表示当前位置是否走过
book[x][y] = 1;
//3.走到最后一个地方,即右下角
if(x == row-1 && y == col-1){
//4.一条新的路径产生,判断是否是更短的路径,如果是空的则是第一次判断
if(minpath.isEmpty() || path.size() < minpath.size()){
minpath.clear();
for(Node n : path){
minpath.add(n);
}
}
}
//5.继续搜索(x,y)的前后左右四个方向
Getminpath(mat,row,col,x+1,y,book,path,minpath);
Getminpath(mat,row,col,x-1,y,book,path,minpath);
Getminpath(mat,row,col,x,y+1,book,path,minpath);
Getminpath(mat,row,col,x,y-1,book,path,minpath);
//6.把当前位置从路径删除,寻找新的路径
path.remove(path.size()-1);
//当前没走过该路
book[x][y] = 0;
}
}