panghu week02 总结笔记

发布时间 2023-12-31 17:35:50作者: Paualf

Algorthim:

N皇后:

思路:
step: 先放第一排,有n种放置的可能性
然后放第二排,放第二排的时候需要检查是否可以放置,如果不可以放置,则continue

func solveNQueens(n int) [][]string {
    bd := make([][]string,n)
    for i := range bd {
        bd[i] = make([]string,n)
        for j := range bd[i] {
            bd[i][j] = "."
        }
    }

    res := [][]string{}
    helper(0,bd,&res,n)
    return res
}

func helper(start int,bd [][]string,res *[][]string,n int) {
    if start == n {
        temp := make([]string,len(bd))
        for i := 0;i < n;i++ {
            temp[i] = strings.Join(bd[i],"")
        }
        *res = append(*res,temp)
        return
    }

    for i := 0;i < n;i ++ {
        if isValid(start,i,n,bd) {
            bd[start][i] = "Q"
            helper(start + 1,bd,res,n)
            bd[start][i] = "."
        }
    }
}

/*
    step: 先放第一排,有n种放置的可能性
    然后放第二排,放第二排的时候需要检查是否可以放置,如果不可以放置,则continue
*/

func isValid(row, col,n int, chessboard [][]string) bool {
	for i := 0; i < row; i++ {
		if chessboard[i][col] == "Q" {
			return false
		}
	}
	for i, j := row-1, col-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
		if chessboard[i][j] == "Q" {
			return false
		}
	}
	for i, j := row-1, col+1; i >= 0 && j < n; i, j = i-1, j+1 {
		if chessboard[i][j] == "Q" {
			return false
		}
	}
	return true
}

java 单元测试:

Powermock mock 静态方法的时候我遇到的问题:
not prepared for test 导入的test包不支持powermock
import org.junit.jupiter.api.Test; // 这个Test包不支持powerMock
需要修改为 import org.junit.Test;

然后后面有遇到 NoSuchMethodError,版本不兼容导致的,替换成了

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.10.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>

参考资料:
Java单元测试技巧之PowerMock
Java单元测试实战
LLT补充时遇到的困难与解决办法
如何解决NoSuchMethodError