题解 | #牛吃草问题#
牛吃草问题
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); } } }