알고리즘
2차원 배열 인덱스 조합 구하기
leeeehhjj
2023. 5. 14. 17:41
2차원 배열의 위치들 중 k 개의 위치를 뽑고 싶을 때 사용하는 공식
예를들어 2*3 크기의 배열이 있다고 하면
0 1 2
3 4 5
처럼 각 위치에 인덱스를 부여하면 2차원 배열을 1차원 배열처럼 생각해서 조합을 구할 수 있다.
import java.util.Scanner;
public class TwoDim_comb {
static int[][] result;
static boolean[][] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); //배열의 행
int m = sc.nextInt(); //배열의 열
int k = sc.nextInt(); //k개의 위치 뽑기
result = new int[k][2];
visited = new boolean[n][m];
dfs(0, n,m,k, 0);
}
static void dfs(int depth, int n, int m, int k, int idx) {
if (depth == k) {
return;
}
for (int i = idx; i < n*m; i++) {
int x = i/m;
int y = i%m;
if (!visited[x][y]) {
visited[x][y] = true;
result[depth][0] = x;
result[depth][1] = y;
dfs(depth+1, n, m, k, i+1);
visited[x][y] = false;
}
}
}
}