图的编程基础代码
1.图的DFS和BFS代码
public class Test {
private Set<Node> visited = new HashSet<>();
// 图的 DFS
public List<Integer> preorder(Node root) {
ArrayList<Integer> res = new ArrayList<>();
if (root ==null) return res;
dfs(root, res);
return res;
}
private void dfs(Node node, List<Integer> res) {
if (node == null) return;
// 处理当前遍历的节点
res.add(node.val);
visited.add(node);
for (Node child : node.children) {
if (!visited.contains(child)) dfs(child, res);
}
}
// 图的 BFS
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
visited.add(root);
while (!queue.isEmpty()) {
// 每轮循环遍历处理一层的节点
int size = queue.size();
List<Integer> levelNodes = new ArrayList<>();
for (int i = 0; i < size; i++) {
Node curr = queue.poll();
levelNodes.add(curr.val);
for (Node child : curr.children) {
if (!visited.contains(child)) queue.offer(child);
visited.add(child);
}
}
res.add(levelNodes);
}
return res;
}
public static void main(String[] args) {
Node node5 = new Node(5);
Node node6 = new Node(6);
List<Node> children2 = Arrays.asList(node5, node6);
Node node2 = new Node(2);
node2.children = children2;
Node node4 = new Node(4);
Node node3 = new Node(3);
List<Node> children1 = Arrays.asList(node2, node3, node4);
Node root = new Node(1);
root.children = children1;
node5.children = Arrays.asList(root);
List<List<Integer>> res = new Test().levelOrder(root);
System.out.println(res);
}
}
2.二维数组与数组之间转换
1.二维转一维:
arr[i][j] 与 nums[index]
index = i * cols + j ;//cols表示列数总和
2.一维转二维:
nums[index]与arr[i][j]
i = index / cols;
j = index % cols;
3.二维数组四联通(保证索引合法)
public class Test {
public static void main(String[] args) {
}
public static void printAgj(int[][] arr , int i , int j){
int rows = arr.length;
int cols = arr[0].length;
//顺序是上 - > 下 -> 左 -> 右
int[][] directions = {{-1,0} , {1,0} , {0,-1} , {0,1}};
for(int[] dir : directions){
int row = i + dir[0];
int col = j + dir[1];
if(row >= 0 && col >= 0 && row < rows && col < cols){
System.out.println(arr[row][col]);
}
}
}
}
4.二维数组八联通(保证索引合法)
public class Test {
public static void main(String[] args) {
}
public static void printAgj(int[][] arr , int i , int j){
int rows = arr.length;
int cols = arr[0].length;
//上 -> 下 -> 左 -> 右 -> 左上 -> 右上 -> 左下 -> 右下
int[][] directions = {{-1,0} , {1,0} , {0,-1} , {0,1},
{-1,-1} , {-1,1} ,{1,-1} , {1,1}};
for(int[] dir : directions){
int row = i + dir[0];
int col = j + dir[1];
if(row >= 0 && col >= 0 && row < rows && col < cols){
System.out.println(arr[row][col]);
}
}
}
}