题解 | #牛吃草问题#

牛吃草问题

https://www.nowcoder.com/practice/c6e33216019a4ea9bf4015e9868dd225

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */
    private HashMap<Integer,Boolean> cols=new HashMap();
    private HashMap<Integer,Boolean> l2r=new HashMap();
    private HashMap<Integer,Boolean> r2l=new HashMap();
    private int n,ans;
    public int totalNCow (int n) {
        this.n=n;
        dfs(0);
        return ans;
    }
    public void dfs(int i){
        if(i==n){
            ans++;
            return;
        }
        for(int j=0;j<n;j++){
            if(cols.get(j)!=null) continue;
            if(l2r.get(i-j)!=null) continue;
            if(r2l.get(i+j)!=null) continue;
            cols.put(j,true);
            l2r.put(i-j,true);
            r2l.put(i+j,true);
            dfs(i+1);
            cols.remove(j);
            l2r.remove(i-j);
            r2l.remove(i+j);
        }
    }
}

全部评论

相关推荐

07-23 11:23
门头沟学院 Java
点赞 评论 收藏
分享
06-07 19:59
门头沟学院 C++
补药卡我啊😭:都快15年前的了还在11新特性
你的简历改到第几版了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务