P1123(DFS+回溯算法)

import java.util.Scanner;

/**
 * P1123取数求和
 * DFS+回溯
 * 解决问题:求最优解,需要遍历每一种可能,然后排除不合理的情况。
 * 实质是递归。
 */
public class P1123 {
	static int T,n,m,ans;
	static int[][] map;
	static int[][] dir = {
   
   {-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};//八个方向
	static boolean[][] use;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		T = sc.nextInt();
		for(int test_case = 1;test_case<=T;test_case++) {
			n = sc.nextInt();
			m = sc.nextInt();
			ans = 0;
			map = new int[n+1][m+1];
			use = new boolean[n+3][m+3];
			for(int i=1;i<=n;i++) {
				for(int j=1;j<=m;j++) {
					map[i][j] = sc.nextInt();
				}
			}
			
			dfs(1,1,0);
			System.out.println("#"+test_case+" "+ans);
		}
	}
	
	public static void dfs(int x,int y,int z) {
		if(x>n) {
			ans = Math.max(ans, z);					
			return ;
		}
		int xx = x,yy = y+1;;
		if(yy>m) {
			xx++;
			yy = 1;
		}
		if(!isVal(x,y)) {
			use[x][y] = true;
			dfs(xx,yy,z+map[x][y]);
			use[x][y] = false;
		}
		dfs(xx,yy,z);
	}
	
	public static boolean isVal(int x,int y) {
		for(int i=0;i<8;i++) {
			if(use[x+dir[i][0]][y+dir[i][1]]==true) {
				return true;
			}
		}
		return false;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_28635317/article/details/111554899
今日推荐